Login

Fuzzy Date Diff Template Filter

Author:
zain
Posted:
March 1, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.