Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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