Skip to content

@shazow /gist:240045
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Ported John Resig's Javascript pretty_date function to Python.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.