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. Querying datetime aware objects in your local timezone by jayliew 1 year, 11 months ago
  2. Past days template filter by ramen 4 years, 5 months ago
  3. Template tag to create mailto links with options by celopes 4 years, 10 months ago
  4. email_links by sansmojo 6 years, 10 months ago
  5. Date/time util template filters by marinho 6 years, 5 months ago

Comments

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

#

cse35959 (on January 30, 2014):

args['days_since'] = dayssince(profile.date_joined) Error:

unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'

#

(Forgotten your password?)