public
Created

Ported John Resig's Javascript pretty_date function to Python.

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
from datetime import datetime
import time
import math
 
def pretty_date(t):
"""
Take a datetime object or epoch time int, return a string representing
how long ago the date was.
 
Inspired by: http://ejohn.org/files/pretty.js
"""
if isinstance(t, datetime):
t = time.mktime(t.timetuple())
 
diff = time.time() - t
day_diff = int(diff / 86400)
 
return day_diff == 0 and (
diff < 60 and "just now" or \
diff < 120 and "1 minute ago" or \
diff < 3600 and "%d minutes ago" % int(diff / 60) or \
diff < 7200 and "1 hour ago" or \
diff < 86400 and "%d hours ago" % int(diff / 3600)) or \
day_diff == 1 and "yesterday" or \
day_diff < 7 and "%d days ago" % day_diff or \
day_diff < 31 and "%d weeks ago" % math.ceil(day_diff / 7) or \
"%d months ago" % math.ceil(day_diff / 30)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.