Skip to content

Instantly share code, notes, and snippets.

@recall704
Forked from borgstrom/human_time_duration.py
Created October 13, 2020 14:57
Show Gist options
  • Save recall704/e3fd1c5b4b8673ed5429b4c82cf601c5 to your computer and use it in GitHub Desktop.
Save recall704/e3fd1c5b4b8673ed5429b4c82cf601c5 to your computer and use it in GitHub Desktop.
Python: Convert seconds (duration) to human readable string
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment