Here's my code from Py-StackExchangePy-StackExchange, in Python:
def format_relative_date(date):
"""Takes a datetime object and returns the date formatted as a string e.g. "3 minutes ago", like the real site.
This is based roughly on George Edison's code from StackApps:
httphttps://stackapps.com/questions/1009/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site/1018#1018"""
now = datetime.now()
diff = (now - date).seconds
# Anti-repetition! These simplify the code somewhat.
plural = lambda d: 's' if d != 1 else ''
frmt = lambda d: (diff / float(d), plural(diff / float(d)))
if diff < 60:
return '%d second%s ago' % frmt(1)
elif diff < 3600:
return '%d minute%s ago' % frmt(60)
elif diff < 86400:
return '%d hour%s ago' % frmt(3600)
elif diff < 172800:
return 'yesterday'
else:
return date.strftime('M j / y - H:i')