Created
March 24, 2012 21:48
-
-
Save alexmic/2188350 to your computer and use it in GitHub Desktop.
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 math | |
def friendly_ago_string(d): | |
""" | |
Returns a friendly string like "8 minutes ago" representing the | |
differences between now and d. | |
""" | |
if not d or not isinstance(d, datetime): | |
return None | |
ending = lambda diff: diff == 1 and " ago" or "s ago" | |
rint = lambda r, v: int(math.ceil(r)) if (r+1) % int(r+1) >= v\ | |
else int(math.floor(r)) | |
dt = datetime.now().replace(tzinfo=None) - d.replace(tzinfo=None) | |
days, seconds = dt.days, dt.seconds | |
years, months, weeks, hours, mins = (rint(days/float(365), 0.6), | |
rint(days/float(30) , 0.85), | |
rint(days/float(7) , 0.85), | |
rint(seconds/float(3600), 0.96), | |
rint(seconds/float(60), 0.99)) | |
if years > 0: | |
return str(years) + " year" + ending(years) | |
if months > 0: | |
return str(months) + " month" + ending(months) | |
elif weeks > 0: | |
return str(weeks) + " week" + ending(weeks) | |
elif days > 0: | |
return str(days) + " day" + ending(days) | |
elif hours > 0: | |
return str(hours) + " hour" + ending(hours) | |
elif mins > 0: | |
return str(mins) + " min" + ending(mins) | |
else: | |
return str(seconds) + " sec" + ending(seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment