Join Login Create a Request

Django, Python how to display date time in "time ago" format

Register a Django template tag in any app.

from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.filter(name='ago')
def ago(value):
    now = datetime.now()
    difference = now - value.replace(tzinfo=None)
    if difference <= timedelta(minutes=1):
        return 'just now'
    return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}

Related Snippets