Skip to content

Instantly share code, notes, and snippets.

@glyphobet
Forked from mwhooker/elapsed_time.py
Created June 3, 2012 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glyphobet/2862999 to your computer and use it in GitHub Desktop.
Save glyphobet/2862999 to your computer and use it in GitHub Desktop.
humanize elapsed time
def elapsed_time(start, end):
"""
>>> from datetime import datetime
>>> elapsed_time(datetime(2000, 1, 1), datetime(2000, 1, 1, 20, 15))
'20 hours, and 15 minutes'
>>> elapsed_time(datetime(2000, 1, 1), datetime(2000, 1, 1, 0, 1))
'1 minute'
>>> elapsed_time(datetime(2000, 1, 1), datetime(2000, 1, 2, 0, 1))
'1 day, and 1 minute'
>>> elapsed_time(datetime(2000, 1, 1), datetime(2000, 1, 2, 2, 3, 4))
'1 day, 2 hours, 3 minutes, and 4 seconds'
"""
assert start < end
td = end - start
out = []
if td.days:
out.append('%d day%s' % (td.days, 's' if td.days > 1 else ''))
modulor = td.seconds
moduland = 3600
for label in ('hour', 'minute', 'second'):
amount, modulor = divmod(modulor, moduland)
if amount:
out.append('%d %s%s' % (amount, label, 's' if amount > 1 else ''))
moduland /= 60
if len(out) > 1:
out[-1] = "and %s" % out[-1]
return ', '.join(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment