Search code examples
pythondjangodjango-template-filters

Django create template filter for nice time


I know there's timesince filter.

But I want something that returns this:

  • just few seconds ago
  • X minutes ago
  • X hours ago
  • on $day_name
  • X weeks ago
  • X months ago

Examples:

  • just few seconds ago
  • 37 minutes ago
  • 2 hours ago
  • yesterday
  • on Thursday
  • 1 week ago
  • 7 months ago

How can I implement something like this?


Solution

  • Not sure if it ticks all your boxes, but there's a tag naturaltime in the django.contrib.humanize template tags that should do this:

    https://docs.djangoproject.com/en/dev/ref/contrib/humanize/#naturaltime

    settings.py

    INSTALLED_APPS = {
        ...
        'django.contrib.humanize',
    }
    

    template.html

    {% load humanize %}
    {{ model.timefield|naturaltime }}