Skip to content

Instantly share code, notes, and snippets.

@chroto
Created July 13, 2012 20:09
Show Gist options
  • Save chroto/3107097 to your computer and use it in GitHub Desktop.
Save chroto/3107097 to your computer and use it in GitHub Desktop.
timedelta functions
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