Created
October 26, 2011 09:38
-
-
Save rmoch/1315904 to your computer and use it in GitHub Desktop.
Natural time since i18n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With Django 1.4 and time zone support you need to replace
with
where 'timezone' is imported with