Custom Django filters: displaying a date as “[time delta] ago”
I’m working on a project based on Django, these days. This framework simplifies developing web applications by a great measure, and is very flexible.
One example of this flexibility is the ability to add new functionality to template syntax. For example, I needed a way to display a date/time as a difference to the current one (“19 days ago”, “10 hours ago”).
Turns out there’s a way to do this in Django: as soon as a need can be generalized, it’s probably in there somewhere, or on djangosnippets. It’s the template filter “timesince“. Basically, in the template, you do:
{{ mydate|timesince }} ago
and it will display your date as said above. Problem is, the string is too long for my needs (it will display “19 days, 10 hours” when I need only “19 days”). So I wrapped the function in another one, in a file place under an app of my project, as explained here. Here’s the content:
from django import template from django.utils.timesince import timesince
register = template.Library()
@register.filter(name='ago')
def ago(date):
ago = timesince(date)
# selects only the first part of the returned string
return ago.split(",")[0] + " ago"
I place that under “myproject/myapp/templatetags/my_date_filter.py”. I also created an empty file __init__.py under templatetags, too. Then, in the template, I may do:
{% load my_date_filter %}
...
{% mydate|ago %}
and I get the shortened string.
Django is full of “extension points” like such. It’s a lot of fun to work with.

piramida:
That’s a nice solution but I would go with a simpler approach like {{mydate|timesince|truncatewords:2}}
Which is not as full-proof in case timesince returns something malformed, though.
19 February 2009, 4:07 ampiramida:
That’s a nice solution but I would go with a simpler approach like {{mydate|timesince|truncatewords:2|cut(“.”)}}
Which is not as fool-proof in case timesince returns something malformed, though.
19 February 2009, 4:09 amfrancois:
Well I knew of truncatewords but not of ‘cut’. I still have a lot to learn about Django
(Clusterify is my first real project using it)
I posted this mostly because I like the multiple ways in which you can extend the framework.
19 February 2009, 10:46 amRyan:
I actually made a custom filter too, I just prefer being able to slap a single filter on a date object instead of having to put three on there.
13 September 2009, 3:06 pm