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. Timedelta template tag by dballanc 6 years, 11 months ago
  2. UTC-based astimezone filter by miracle2k 2 years, 5 months ago
  3. Humanize lists of strings in templates by ChipX86 6 years, 10 months ago
  4. Human format Date representation by sachingupta006 2 years ago
  5. HTML/JS template filter to show localized dates/times by mback2k 5 years ago

Comments

micklinghoff (on February 21, 2011):

really cool, thanks a lot for posting!

#

(Forgotten your password?)