Created
May 19, 2019 17:08
-
-
Save atdt/7482a2ed3b0e85379d269b1ed47325e3 to your computer and use it in GitHub Desktop.
Human-readable duration
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_duration(seconds): | |
if seconds <= 1: | |
return '0 seconds' | |
units = ( | |
('day', 86400), | |
('hour', 3600), | |
('minute', 60), | |
('second', 1), | |
) | |
parts = [] | |
for unit, duration in units: | |
n = seconds // duration | |
seconds %= duration | |
if n: | |
parts.append('%d %s' % (n, unit if n == 1 else unit + 's')) | |
if len(parts) > 2: | |
return '%s, and %s' % (', '.join(parts[:-1]), parts[-1]) | |
return ' and '.join(parts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment