Skip to content

Instantly share code, notes, and snippets.

@tonyblundell
Created May 10, 2012 10:43
Show Gist options
  • Save tonyblundell/2652369 to your computer and use it in GitHub Desktop.
Save tonyblundell/2652369 to your computer and use it in GitHub Desktop.
ago: Calculate a '3 hours ago' type string from a python datetime.
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'
@chocolateimage
Copy link

Missing math.floor that means it says 6.889722222222222 hours ago

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment