Skip to content

Instantly share code, notes, and snippets.

@atdt
Created May 19, 2019 17:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atdt/7482a2ed3b0e85379d269b1ed47325e3 to your computer and use it in GitHub Desktop.
Save atdt/7482a2ed3b0e85379d269b1ed47325e3 to your computer and use it in GitHub Desktop.
Human-readable duration
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