[Fixed]-How to display human time (x days ago, or now) in django admin?


You can use extra methods in your model like this:

class Example(models.Model):
    date = models.DateTimeField(auto_now_add=True)

    def get_date(self):
        time = datetime.now()
        if self.created_at.day == time.day:
            return str(time.hour - self.created_at.hour) + " hours ago"
            if self.created_at.month == time.month:
                return str(time.day - self.created_at.day) + " days ago"
                if self.created_at.year == time.year:
                    return str(time.month - self.created_at.month) + " months ago"
        return self.created_at

or you can create some utils functions for do that and just use it in your model method if you want to use in more situations

Here is the documentation for Django admin, here you find all that you need:



There is an accepted answer however I want to suggest another thing who came here for a solution which can be used in templates.

Django has a contrib package called django.contrib.humanize. Add this to your INSTALLED_APPS, then use {% load humanize %} in your template, after that, you can use value|naturaltime template tag. “value” will be your date.

Let’s say content.created, which contains the creation date of your content. It’s a datetimefield object. So, you can use this: content.created|naturaltime. It’ll convert the date e.g from July 14, 2018 11:30 to “3 days 1 hour ago”.

Check it on Django DOCS.


Turns out the template filters can be accessed directly from your Python codebase. Something like this:

from django.contrib.humanize.templatetags import humanize

class Example(models.Model):
    date = models.DateTimeField(auto_now_add=True)

    def get_date(self):
        return humanize.naturaltime(self.date)

The get_date() function can also be located within your CourseAdmin class.


I found this useful

use it in your template, eg. index.html

{{ post.timestamp | timesince }}

Leave a comment