Created
November 21, 2009 07:41
-
-
Save shazow/240045 to your computer and use it in GitHub Desktop.
Ported John Resig's Javascript pretty_date function to Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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