Skip to content

Instantly share code, notes, and snippets.

@codeliger
Last active January 29, 2019 20:26
Show Gist options
  • Save codeliger/2eb2dc96e14578f12eb963479136999c to your computer and use it in GitHub Desktop.
Save codeliger/2eb2dc96e14578f12eb963479136999c to your computer and use it in GitHub Desktop.
seconds_verb = (
(29030400,'year'),
(2419200,'month'),
(604800,'week'),
(86400,'day'),
(3600,'hour'),
(60,'minute'),
(1,'second')
)
def humanize_time(time_in_seconds:int, exclude:list = [], delimiter:str=' ') -> str:
'''
Converts seconds into human readable time
Excludable values:
year, month, week, day, hour, minute, second
Examples:
humanize_time(32144461)
1 year 1 month 1 week 1 day 1 hour 1 minute 1 second
humanize_time(3600, exclude='hour')
60 minutes
'''
pieces = []
for seconds, verb in seconds_verb:
if verb in exclude:
continue
if time_in_seconds < seconds:
continue
value, time_in_seconds = divmod(time_in_seconds, seconds)
pieces.append('{} {}{}'.format(value, verb, 's' if value > 1 else ''))
return delimiter.join(pieces)
print(humanize_time(930000, exclude=['week', 'day', 'minute', 'second']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment