Days Since Filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django import template
import datetime

register = template.Library()

def dayssince(value):
    "Returns number of days between today and value."
    today = datetime.date.today()
    diff  = today - value
    if diff.days > 1:
        return '%s days ago' % diff.days
    elif diff.days == 1:
        return 'yesterday'
    elif diff.days == 0:
        return 'today'
    else:
        # Date is in the future; return formatted date.
        return value.strftime("%B %d, %Y")

register.filter('dayssince', dayssince)

More like this

  1. Fuzzy Date Diff Template Filter by zain 3 years, 2 months ago
  2. Date/time util template filters by marinho 4 years, 6 months ago
  3. Smart i18n date diff (twitter like) by Batiste 3 years, 1 month ago
  4. Past days template filter by ramen 2 years, 6 months ago
  5. Template tag to create mailto links with options by celopes 2 years, 11 months ago

Comments

joe4444 (on March 18, 2007):

I was surprised this filter wasn't part of the built-in filters. It's quite basic and works for my particular needs. If anyone has suggestions for improvement (e.g. internationalization, format for dates older than 30 days, format for future dates, etc.) please leave a comment.

Thanks!

#

vdemeester (on March 19, 2007):

Hi,

there is just a 'little' bug, you have an elif without an if before, and an if after elif..

Thanks for this filter :p

#

rpoulton (on March 22, 2007):

Django has a built-in template filter for 'timesince' which does something similar:

http://www.djangoproject.com/documentation/templates/#timesince

However I like the way you break it down into today/yesterday/etc. Nice one!

#

joe4444 (on April 9, 2007):

vdemeester, thanks for pointing that out. I hastily changed the order of that if statement without fixing the if/elif part. (Fixed now)

rpoulton, I tried using the timesince filter, but when used on a DateField it will return hours (from midnight), which is not what I was after.

I'm glad you both like it. =)

#

(Forgotten your password?)