-
-
Save glyphobet/2862999 to your computer and use it in GitHub Desktop.
humanize elapsed time
This file contains hidden or 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
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