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 4 years, 3 months ago
  2. Past days template filter by ramen 6 years, 9 months ago
  3. Template tag to create mailto links with options by celopes 7 years, 2 months ago
  4. email_links by sansmojo 9 years, 2 months ago
  5. Date/time util template filters by marinho 8 years, 9 months ago

Comments

vdemeester (on March 19, 2007):
<p>Hi, </p> <p>there is just a 'little' bug, you have an elif without an if before, and an if after elif..</p> <p>Thanks for this filter :p</p>

#

cse35959 (on January 30, 2014):
<p>args['days_since'] = dayssince(profile.date_joined) Error:</p> <p>unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'</p>

#

discort (on April 26, 2015):
<p>for better way use</p> <p>from django.utils import timezone</p> <p>today = timezone.now()</p> <p>instead</p> <p>today = datetime.date.today()</p>

#

Please login first before commenting.