Created
May 9, 2018 04:00
-
-
Save borgstrom/936ca741e885a1438c374824efb038b3 to your computer and use it in GitHub Desktop.
Python: Convert seconds (duration) to human readable string
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
TIME_DURATION_UNITS = ( | |
('week', 60*60*24*7), | |
('day', 60*60*24), | |
('hour', 60*60), | |
('min', 60), | |
('sec', 1) | |
) | |
def human_time_duration(seconds): | |
if seconds == 0: | |
return 'inf' | |
parts = [] | |
for unit, div in TIME_DURATION_UNITS: | |
amount, seconds = divmod(int(seconds), div) | |
if amount > 0: | |
parts.append('{} {}{}'.format(amount, unit, "" if amount == 1 else "s")) | |
return ', '.join(parts) |
Good stuff, thanks
Thank you for this.
very helpful! TIL moment,
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!