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 4 years, 3 months ago
  2. Time toggle on mouseover template filter by soniiic 4 years, 2 months ago
  3. Date/time util template filters by marinho 5 years, 7 months ago
  4. Querying datetime aware objects in your local timezone by jayliew 1 year ago
  5. Past days template filter by ramen 3 years, 7 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?)