Skip to content

Instantly share code, notes, and snippets.

@chidiwilliams
Created January 10, 2017 20:53
Show Gist options
  • Save chidiwilliams/b7bda45804645a911773e10cdce8b22d to your computer and use it in GitHub Desktop.
Save chidiwilliams/b7bda45804645a911773e10cdce8b22d to your computer and use it in GitHub Desktop.
Custom Django Filter to present time difference in human friendly form e.g. just now, 4 minutes ago, a month ago.
from django import template
register = template.Library()
@register.filter
def humanTimeDiff(value):
"""
Returns the difference between the datetime value given and now()
in human-readable form
"""
from datetime import datetime, timedelta
from django.utils import timezone
if isinstance(value, timedelta):
delta = value
elif isinstance(value, datetime):
delta = timezone.now() - value
else:
delta = None
if delta:
second_diff = delta.seconds
day_diff = delta.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(int(round(second_diff/60))) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(int(round(second_diff/3600))) + " hours ago"
if day_diff == 1:
return "yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 11:
return "a week ago"
if day_diff < 31:
return str(int(round(day_diff/7))) + " weeks ago"
if day_diff < 46:
return "a month ago"
if day_diff < 365:
return str(int(round(day_diff/30))) + " months ago"
if day_diff < 550:
return "a year ago"
return str(int(round(day_diff/365))) + " years ago"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment