Login

Days Since Filter

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

#

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.