Skip to content

Instantly share code, notes, and snippets.

@jsoa
Created November 5, 2012 13:09
Show Gist options
  • Select an option

  • Save jsoa/4017107 to your computer and use it in GitHub Desktop.

Select an option

Save jsoa/4017107 to your computer and use it in GitHub Desktop.
Django humanized time since filter
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.template.defaultfilters import date, timesince
from django.template import Library
from django.utils.translation import ugettext
register = Library()
@register.filter('humanized_timesince')
def humanized_timesince_filter(value, arg=None):
"""Humanized time since filter.
- Within the hour: `1 minute` to `59 minutes`
- Within the day: `1 hour` to `23 hours`
- Within 48 hours and after a day: `yesterday`
- Within the week, after 48 hours: Day of the week
- After a week: default `timesince` functionality
>>> tnow = datetime(2012, 10, 9, 0, 0, 0 , 0)
>>> datetime.strftime(tnow, '%A')
'Tuesday'
>>> humanized_timesince_filter(datetime(2012, 10, 8, 23, 59, 0, 0), tnow)
u'1 minute'
>>> humanized_timesince_filter(datetime(2012, 10, 8, 23, 1, 0, 0), tnow)
u'59 minutes'
>>> humanized_timesince_filter(datetime(2012, 10, 8, 23, 0, 0, 0), tnow)
u'1 hour'
>>> humanized_timesince_filter(datetime(2012, 10, 8, 1, 0, 0, 0), tnow)
u'23 hours'
>>> humanized_timesince_filter(datetime(2012, 10, 8, 0, 0, 0, 0), tnow)
u'yesterday'
>>> humanized_timesince_filter(datetime(2012, 10, 7, 0, 0, 0, 0), tnow)
u'Sunday'
>>> humanized_timesince_filter(datetime(2012, 10, 3, 0, 0, 0, 0), tnow)
u'Wednesday'
>>> humanized_timesince_filter(datetime(2012, 10, 2, 0, 0, 0, 0), tnow)
u'1 week'
>>> humanized_timesince_filter(datetime(2012, 9, 9, 0, 0, 0, 0), tnow)
u'1 month'
>>> humanized_timesince_filter(datetime(2012, 8, 9, 0, 0, 0, 0), tnow)
u'2 months'
>>> humanized_timesince_filter(datetime(2012, 7, 21, 1, 0, 0, 0), tnow)
u'2 months, 2 weeks'
>>> humanized_timesince_filter(datetime(2011, 10, 1, 0, 0, 0, 0), tnow)
u'1 year'
>>> humanized_timesince_filter(datetime(2011, 6, 1, 0, 0, 0, 0), tnow)
u'1 year, 4 months'
"""
if not value:
return u''
compare_to = type(arg) == datetime and arg or datetime.now()
one_day = compare_to - timedelta(hours=24)
two_days = compare_to - timedelta(hours=48)
week = compare_to - timedelta(days=7)
func, args = timesince, (value, compare_to)
if one_day < value < compare_to:
args = (value, compare_to)
elif two_days < value < compare_to:
return ugettext('yesterday')
elif week < value < compare_to:
func = date
args = (value, 'l')
return func(*args)
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment