Login

Timedelta template tag

Author:
dballanc
Posted:
April 30, 2007
Language:
Python
Version:
.96
Score:
7 (after 7 ratings)

This is tag similar to timesince and timeuntil, which work great until you starting giving timesince dates in the future or timeuntil dates in the past. Timedelta tag will humanize output correctly for both future and past dates using now as a default reference date (or a specified reference date as argument)

now = Apr 27 2007

futuredate = May 5 2007

pastdate = Jan 5 2007

{{ futuredate|timedelta }} will output "in 1 week, 1 day"

{{ pastdate|timedelta }} will output "3 months, 2 weeks ago"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django import template
from django.utils.timesince import timesince
from datetime import datetime

register = template.Library()

def timedelta(value, arg=None):
    if not value:
        return ''
    if arg:
        cmp = arg
    else:
        cmp = datetime.now()
    if value > cmp:
        return "in %s" % timesince(cmp,value)
    else:
        return "%s ago" % timesince(value,cmp)

register.filter('timedelta',timedelta)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 5 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 5 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year ago
  5. Help text hyperlinks by sa2812 1 year, 1 month ago

Comments

Please login first before commenting.