Created
April 23, 2014 20:00
-
-
Save jjmalina/11230205 to your computer and use it in GitHub Desktop.
Format a timedelta into the largest possible unit (weeks is the largest in this case)
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 format_timedelta(td): | |
"""formats a timedelta into the largest unit possible | |
>>> from datetime import timedelta | |
>>> format_timedelta(timedelta(weeks=2)) | |
'2w' | |
>>> format_timedelta(timedelta(weeks=2, minutes=2)) | |
'20162m' | |
>>> format_timedelta(timedelta(days=2)) | |
'2d' | |
>>> format_timedelta(timedelta(days=2, hours=2)) | |
'50h' | |
>>> format_timedelta(timedelta(days=2, hours=2, minutes=1)) | |
'3001m' | |
>>> format_timedelta(timedelta(hours=36)) | |
'36h' | |
>>> format_timedelta(timedelta(hours=24)) | |
'1d' | |
>>> format_timedelta(timedelta(hours=16)) | |
'16h' | |
>>> format_timedelta(timedelta(hours=1)) | |
'1h' | |
>>> format_timedelta(timedelta(minutes=120)) | |
'2h' | |
>>> format_timedelta(timedelta(minutes=90)) | |
'90m' | |
>>> format_timedelta(timedelta(minutes=59)) | |
'59m' | |
>>> format_timedelta(timedelta(minutes=30)) | |
'30m' | |
>>> format_timedelta(timedelta(minutes=1)) | |
'1m' | |
>>> format_timedelta(timedelta(seconds=90)) | |
'90s' | |
>>> format_timedelta(timedelta(seconds=59)) | |
'59s' | |
>>> format_timedelta(timedelta(seconds=1)) | |
'1s' | |
>>> format_timedelta(timedelta(milliseconds=2000)) | |
'2s' | |
>>> format_timedelta(timedelta(milliseconds=999)) | |
'999ms' | |
>>> format_timedelta(timedelta(milliseconds=1)) | |
'1ms' | |
>>> format_timedelta(timedelta(microseconds=2000)) | |
'2ms' | |
>>> format_timedelta(timedelta(microseconds=2500)) | |
'2500us' | |
>>> format_timedelta(timedelta(microseconds=999)) | |
'999us' | |
>>> format_timedelta(timedelta(microseconds=1)) | |
'1us' | |
""" | |
total_seconds = td.total_seconds() | |
units = [(604800, 'w'), (86400, 'd'), (3600, 'h'), (60, 'm'), (1, 's')] | |
for seconds, unit in units: | |
if total_seconds >= seconds and total_seconds % seconds == 0: | |
return "%r%s" % (int(total_seconds / seconds), unit) | |
if total_seconds >= 0.001: | |
if (total_seconds / 0.001) % 1 == 0: | |
return "%r%s" % (int(total_seconds * 1000), 'ms') | |
else: | |
micro = int(total_seconds / 0.000001) | |
micro += int(total_seconds % 0.000001) | |
return "%r%s" % (micro, 'us') | |
return "%r%s" % (int(total_seconds * 1000000), 'us') | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment