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
- Fuzzy Date Diff Template Filter by zain 4 years, 3 months ago
- Time toggle on mouseover template filter by soniiic 4 years, 2 months ago
- Date/time util template filters by marinho 5 years, 7 months ago
- Querying datetime aware objects in your local timezone by jayliew 1 year ago
- Past days template filter by ramen 3 years, 7 months ago
Comments
I was surprised this filter wasn't part of the built-in filters. It's quite basic and works for my particular needs. If anyone has suggestions for improvement (e.g. internationalization, format for dates older than 30 days, format for future dates, etc.) please leave a comment.
Thanks!
#
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
#
Django has a built-in template filter for 'timesince' which does something similar:
http://www.djangoproject.com/documentation/templates/#timesince
However I like the way you break it down into today/yesterday/etc. Nice one!
#
vdemeester, thanks for pointing that out. I hastily changed the order of that if statement without fixing the if/elif part. (Fixed now)
rpoulton, I tried using the timesince filter, but when used on a DateField it will return hours (from midnight), which is not what I was after.
I'm glad you both like it. =)
#