Login

Fuzzy Date Diff Template Filter

Author:
zain
Posted:
March 1, 2009
Language:
Python
Version:
1.0
Tags:
template filter date humanize
Score:
4 (after 4 ratings)

Pass in a date and you get a humanized fuzzy date diff; e.g. "2 weeks ago" or "in 5 months".

The date you pass in can be in the past or future (or even the present, for that matter).

The result is rounded, so a date 45 days ago will be "2 months ago", and a date 400 days from now will be "in 1 year".

Usage:

  • {{ my_date|date_diff }} will give you a date_diff between my_date and datetime.date.today()

  • {{ my_date|date_diff:another_date }} will give you a date_diff between my_date and another_date

Make sure to install this as a template tag and call {% load date_diff %} in your template; see the custom template tag docs if you don't know how to do that.

 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 6 years, 5 months ago
  2. Timedelta template tag by dballanc 8 years, 4 months ago
  3. Date/time util template filters by marinho 7 years, 9 months ago
  4. humanize time difference (how long ago) by supsupmo 7 years, 11 months ago
  5. Days Since Filter by joe4444 8 years, 5 months ago

Comments

ZaphodB (on March 13, 2009):

works with datetime objects after

date=timestamp.date()

delta=date - compare_with

#

Please login first before commenting.