Created
May 10, 2012 10:43
-
-
Save tonyblundell/2652369 to your computer and use it in GitHub Desktop.
ago: Calculate a '3 hours ago' type string from a python datetime.
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
import datetime | |
def ago(t): | |
""" | |
Calculate a '3 hours ago' type string from a python datetime. | |
""" | |
units = { | |
'days': lambda diff: diff.days, | |
'hours': lambda diff: diff.seconds / 3600, | |
'minutes': lambda diff: diff.seconds % 3600 / 60, | |
} | |
diff = datetime.datetime.now() - t | |
for unit in units: | |
dur = units[unit](diff) # Run the lambda function to get a duration | |
if dur > 0: | |
unit = unit[:-dur] if dur == 1 else unit # De-pluralize if duration is 1 ('1 day' vs '2 days') | |
return '%s %s ago' % (dur, unit) | |
return 'just now' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Missing math.floor that means it says 6.889722222222222 hours ago