Humanized and localized timesince template filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import datetime

from django import template
from django.utils.translation import ugettext, ungettext

register = template.Library()


@register.filter(name='timesince_human')
def humanize_timesince(date):
    delta = datetime.datetime.now() - date

    num_years = delta.days / 365
    if (num_years > 0):
        return ungettext(u"%d year ago", u"%d years ago", num_years) % num_years

    num_weeks = delta.days / 7
    if (num_weeks > 0):
        return ungettext(u"%d week ago", u"%d weeks ago", num_weeks) % num_weeks

    if (delta.days > 0):
        return ungettext(u"%d day ago", u"%d days ago", delta.days) % delta.days

    num_hours = delta.seconds / 3600
    if (num_hours > 0):
        return ungettext(u"%d hour ago", u"%d hours ago", num_hours) % num_hours

    num_minutes = delta.seconds / 60
    if (num_minutes > 0):
        return ungettext(u"%d minute ago", u"%d minutes ago", num_minutes) % num_minutes

    return ugettext(u"just a few seconds ago")

More like this

  1. Age - custom filter by realmac 5 years, 4 months ago
  2. Timedelta template tag by dballanc 6 years ago
  3. Optimized humanize naturalday filter by c2j 3 years, 8 months ago
  4. Smart i18n date diff (twitter like) by Batiste 4 years, 1 month ago
  5. BabelMiddleware by skam 5 years, 10 months ago

Comments

micklinghoff (on February 21, 2011):

really cool, thanks a lot for posting!

#

(Forgotten your password?)