Created
July 13, 2012 20:09
-
-
Save chroto/3107097 to your computer and use it in GitHub Desktop.
timedelta functions
This file contains 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 human_time(td): | |
""" | |
Return a more human readable version of a timedelta instance | |
""" | |
ret_str = "" | |
translate_tuple = [ | |
"day", | |
"hour", | |
"minute", | |
"second"] | |
time_tuple = get_days_hours_minutes(td) | |
for val in time_tuple: | |
epoch = translate_tuple.pop(0) | |
if val: | |
ret_str += "{0} {epoch}".format(val, epoch=epoch) | |
ret_str += "s " if val is not 1 else " " | |
return ret_str | |
def get_days_hours_minutes(td): | |
""" | |
Timedelta objects only have seconds and days. This takes a timedelta | |
instance and returns a tuple of days, hours, minutes, seconds | |
>>> from datetime import timedelta | |
>>> td = timedelta(seconds=0) | |
>>> get_days_hours_minutes(td) | |
(0, 0, 0, 0) | |
>>> td = timedelta(days=1, hours=1, minutes=1, seconds=1) | |
>>> get_days_hours_minutes(td) | |
(1, 1, 1, 1) | |
>>> td = timedelta(days=0, hours=25, minutes=0, seconds=0) | |
>>> get_days_hours_minutes(td) | |
(1, 1, 0, 0) | |
""" | |
minutes, seconds = divmod(td.days * 86400 + td.seconds, 60) | |
hours, minutes = divmod(minutes, 60) | |
days, hours = divmod(hours, 24) | |
return days, hours, minutes, seconds | |
def total_seconds(td): | |
""" | |
This gives equivalent functionality as timedelta.total_seconds in | |
Python >= 2.7 | |
http://docs.python.org/library/datetime.html | |
>>> from datetime import timedelta | |
>>> td = timedelta(days=1) | |
>>> int(total_seconds(td)) | |
86400 | |
""" | |
return (td.microseconds + | |
(td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment