Fuzzy Date Diff 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
33
34
from django import template
from django.utils.translation import ungettext, ugettext
import datetime

register = template.Library()

@register.filter
def date_diff(timestamp, to=None):
    if not timestamp:
        return ""
    
    compare_with = to or datetime.date.today()
    delta = timestamp - compare_with
    
    if delta.days == 0: return u"today"
    elif delta.days == -1: return u"yesterday"
    elif delta.days == 1: return u"tomorrow"
    
    chunks = (
        (365.0, lambda n: ungettext('year', 'years', n)),
        (30.0, lambda n: ungettext('month', 'months', n)),
        (7.0, lambda n : ungettext('week', 'weeks', n)),
        (1.0, lambda n : ungettext('day', 'days', n)),
    )
    
    for i, (chunk, name) in enumerate(chunks):
        if abs(delta.days) >= chunk:
            count = abs(round(delta.days / chunk, 0))
            break

    date_str = ugettext('%(number)d %(type)s') % {'number': count, 'type': name(count)}
    
    if delta.days > 0: return "in " + date_str
    else: return date_str + " ago"

More like this

  1. Smart i18n date diff (twitter like) by Batiste 4 years, 1 month ago
  2. Timedelta template tag by dballanc 6 years ago
  3. Date/time util template filters by marinho 5 years, 6 months ago
  4. Python Calendar wrapper template tag by dokterbob 4 years ago
  5. Calendar table by fauxparse 5 years ago

Comments

ZaphodB (on March 13, 2009):

works with datetime objects after

date=timestamp.date()

delta=date - compare_with

#

Batiste (on March 31, 2009):

Hello:

modified version here:

http://www.djangosnippets.org/snippets/1409/

#

(Forgotten your password?)