Login

Days Since Filter

Author:
joe4444
Posted:
March 18, 2007
Language:
Python
Version:
Pre .96
Tags:
filter
Score:
8 (after 8 ratings)

Very simple filter that returns one of the following by default:

  1. # days ago
  2. yesterday
  3. today
  4. January 01, 2007

Example template code:

This thread was started {{ post.date_created|dayssince }}.
This thread was started today.

E-mail sent: {{ email.date_sent|dayssince|capfirst }}
E-mail sent: Yesterday

Object created: {{ obj.date_created|dayssince|upper }}
Object created: 12 DAYS AGO

User's bogus birthday: {{ user.get_profile.bday|dayssince }}
User's bogus birthday: April 20, 3030
 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 3 years, 1 month ago
  2. Past days template filter by ramen 5 years, 7 months ago
  3. Template tag to create mailto links with options by celopes 6 years ago
  4. Date/time util template filters by marinho 7 years, 7 months ago
  5. email_links by sansmojo 8 years, 1 month 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'

#

discort (on April 26, 2015):

for better way use

from django.utils import timezone

today = timezone.now()

instead

today = datetime.date.today()

#

Please login first before commenting.