Skip to content

Instantly share code, notes, and snippets.

@rmoch
Created October 26, 2011 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmoch/1315904 to your computer and use it in GitHub Desktop.
Save rmoch/1315904 to your computer and use it in GitHub Desktop.
Natural time since i18n
# Natural time since template tag i18n
from django import template
from django.utils.encoding import force_unicode
from django.utils.translation import ungettext, ugettext as _
register = template.Library()
# from http://anandnalya.com/2009/05/20/humanizing-the-time-difference-in-django/
MOMENT = 60 # duration in seconds within which the time difference
# will be rendered as 'a moment ago'
@register.filter
def natural_timesince(value):
"""Finds the difference between the datetime value given and now()
and returns appropriate humanize form."""
if isinstance(value, datetime.datetime):
delta = datetime.datetime.now() - value
if delta.days > 6:
return value.strftime("%b %d") # May 15
if delta.days > 1:
return value.strftime("%A") # Wednesday
elif delta.days == 1:
return _(u"yesterday") # yesterday
elif delta.seconds > 3600:
hours = delta.seconds / 3600
return force_unicode(ungettext(u"%(hours)d hour ago", "%(hours)d hours ago", hours) % {'hours': hours})
elif delta.seconds > MOMENT:
minutes = delta.seconds/60
return force_unicode(ungettext(u"%(minutes)d minute ago", u"%(minutes)d minutes ago", minutes) % {
'minutes': minutes})
else:
return force_unicode(_(u"a moment ago"))
return template.defaultfilters.date(value)
else:
return str(value)
@tgdn
Copy link

tgdn commented Mar 30, 2012

With Django 1.4 and time zone support you need to replace


with

where 'timezone' is imported with


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment