Created
January 17, 2014 03:02
-
-
Save daleobrien/8467703 to your computer and use it in GitHub Desktop.
Format a `timedelta` object to a string, such that only the significant portion is displayed.
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 timedelta_format(td_object): | |
''' | |
Format a timedelta object to a string such that only the significant | |
portion of it is displayed. | |
Some examples: | |
12 days, 12:55:00 -> 12 days | |
1 day, 12:00:00 -> 1 day | |
1 day, 1:01:00 -> 1 day, 1 hour | |
1:00:00 -> 60 minutes | |
''' | |
seconds = int(td_object.total_seconds()) | |
PERIODS = [('year', 60*60*24*365), ('month', 60*60*24*30), | |
('day', 60*60*24), ('hour', 60*60), ('minute', 60), | |
('second', 1)] | |
strings = [] | |
found = False | |
skipped = False | |
last_period_value = 0 | |
for period_name, period_seconds in PERIODS: | |
if seconds > period_seconds: | |
if found and skipped: | |
break | |
period_value, seconds = divmod(seconds, period_seconds) | |
if period_value == 1: | |
strings.append("%s %s" % (period_value, period_name)) | |
else: | |
if last_period_value > 2 and strings: | |
last_period_value = period_value | |
break | |
strings.append("%s %ss" % (period_value, period_name)) | |
if period_value > 1: | |
last_period_value = period_value | |
break | |
last_period_value = period_value | |
found = True | |
skipped = False | |
else: | |
skipped = True | |
return " and ".join(strings[:2]) | |
if __name__ == "__main__": | |
assert(timedelta_format( | |
timedelta(days=12, hours=12, minutes=55)) == '12 days') | |
assert(timedelta_format( | |
timedelta(days=1, hours=12)) == '1 day and 12 hours') | |
assert(timedelta_format( | |
timedelta(days=1, hours=1, minutes=1)) == '1 day and 1 hour') | |
assert(timedelta_format( | |
timedelta(days=0, hours=1)) == '60 minutes') | |
assert(timedelta_format( | |
timedelta(days=0, hours=12)) == '12 hours') | |
assert(timedelta_format( | |
timedelta(days=0, hours=12, minutes=34)) == '12 hours') | |
assert(timedelta_format( | |
timedelta(days=0, hours=1, seconds=6)) == '1 hour') | |
assert(timedelta_format( | |
timedelta(days=0, hours=1, minutes=34)) == '1 hour and 34 minutes') | |
assert(timedelta_format( | |
timedelta(days=0, hours=0, minutes=1, seconds=12)) == | |
'1 minute and 12 seconds') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment