Skip to content

Instantly share code, notes, and snippets.

@larsyencken
Created September 23, 2011 03:53
Show Gist options
  • Save larsyencken/1236717 to your computer and use it in GitHub Desktop.
Save larsyencken/1236717 to your computer and use it in GitHub Desktop.
Pretty print time in seconds
def human_time(s):
"""
Given a time interval in seconds, return it pretty-printed.
>>> human_time(3.234)
'3.2s'
>>> human_time(91)
'1m 31s'
>>> human_time(3691)
'1h 1m'
"""
if s < 3:
return '%.02fs' % s
if s < 10:
return '%.01fs' % s
if s < 60:
return '%.0fs' % s
s = int(s)
m, s = divmod(s, 60)
if m < 60:
return '%dm %ds' % (m, s)
h, m = divmod(m, 60)
return '%dh %dm' % (h, m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment