Created
December 10, 2015 20:50
-
-
Save steinnes/d46da0d99090589e2088 to your computer and use it in GitHub Desktop.
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_string(delta): | |
''' | |
Return a nice human readable "X days[, Y hours [and Y minutes]]" string | |
for a given datetime.timedelta | |
''' | |
minutes = delta.seconds // 60 | |
hours = delta.seconds // 3600 | |
minutes -= hours * 60 # subtract hours | |
days = delta.days | |
ret = '{days}{hours}{minutes}' | |
tvars = dict(days='', hours='', minutes='') | |
if days != 0: | |
if hours != 0: | |
if minutes != 0: | |
fmt = '{ndays} {daystr}, ' | |
else: | |
fmt = '{ndays} {daystr} and ' | |
else: | |
fmt = '{ndays} {daystr} ' | |
tvars['days'] = fmt.format(ndays=days, daystr='days' if days > 1 else 'day') | |
if hours != 0: | |
if minutes != 0: | |
fmt = '{nhours} {hourstr} and ' | |
else: | |
fmt = '{nhours} {hourstr} ' | |
tvars['hours'] = fmt.format(nhours=hours, hourstr='hours' if hours > 1 else 'hour') | |
if minutes != 0: | |
tvars['minutes'] = '{} {}'.format(minutes, 'minutes' if minutes > 1 else 'minute') | |
return ret.format(**tvars).strip() # strip possible trailing whitespace |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment