A Better Timesince Template Filter For Django

Django's timesince filter: 2 hours, 38 minutes

My timesince filter: 2 hours ago

If you like my version here's how to use it:

Make a directory (if one doesn't already exist) in your app's directory called "templatetags" --- it should live in the same level as models.py, views.py, etc. Create a file called app_extras.py and put the following code into it.

from django import template
import datetime, pytz

register = template.Library()

@register.filter(name='time_since')
def time_since(date, default="just now"):
    now = datetime.datetime.utcnow().replace(tzinfo = pytz.utc)
    diff = now - date
    periods = (
        (diff.days / 365, "year", "years"),
        (diff.days / 30, "month", "months"),
        (diff.days / 7, "week", "weeks"),
        (diff.days, "day", "days"),
        (diff.seconds / 3600, "hour", "hours"),
        (diff.seconds / 60, "minute", "minutes"),
        (diff.seconds, "second", "seconds"),
    )
    for period, singular, plural in periods:
        if period:
            return "%d %s ago" % (period, singular if period == 1 else plural)
    return default

In your template you'll load these extra template filters like this:

{% load poll_extras %}

And then while rendering the form field I used the variable I just created like this:

{{ article.pub_date|time_since }}