Skip to content

Instantly share code, notes, and snippets.

@arahaya
Created February 9, 2013 17:34
Show Gist options
  • Save arahaya/4746214 to your computer and use it in GitHub Desktop.
Save arahaya/4746214 to your computer and use it in GitHub Desktop.
Django since filter
import datetime
from django import template
from django.utils.timezone import is_aware, utc
from django.utils.translation import ungettext, ugettext
register = template.Library()
@register.filter(is_safe=False)
def since(date, stop_at_month=False):
"""Formats a date as the time since that date (i.e. "4 days ago").
Stolen from
* django.utils.timesince.py
* https://github.com/playframework/play/blob/master/framework/src/play/templates/JavaExtensions.java
* http://djangosnippets.org/snippets/2275/
"""
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(date, datetime.datetime):
date = datetime.datetime(date.year, date.month, date.day)
now = datetime.datetime.now(utc if is_aware(date) else None)
if now < date:
# date is in the future compared to now, stop processing.
return u''
delta = now - date
seconds = delta.days * 24 * 60 * 60 + delta.seconds
#if seconds < 60:
# return ugettext(u"just a few seconds ago")
if seconds < 60:
return ungettext(u"%d second ago", u"%d seconds ago", seconds) % seconds
if seconds < 3600: # 60 * 60
minutes = seconds // 60
return ungettext(u"%d minute ago", u"%d minutes ago", minutes) % minutes
if seconds < 86400: # 24 * 30 * 30
hours = seconds // 3600
return ungettext(u"%d hour ago", u"%d hours ago", hours) % hours
if seconds < 172800: # 2 * 24 * 60 * 60
return ugettext(u"yesterday")
if seconds < 259200: # 3 * 24 * 60 * 60
return ugettext(u"2 days ago")
if seconds < 2592000: # 30 * 24 * 60 * 60
days = seconds // 86400
return ungettext(u"%d day ago", u"%d days ago", days) % days
if stop_at_month:
return date.date()
if seconds < 31536000: # 365 * 24 * 60 * 60
months = seconds // 2592000
return ungettext(u"%d month ago", u"%d months ago", months) % months
years = seconds // 31536000
return ungettext(u"%d year ago", u"%d years ago", years) % years
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment