Skip to content

Instantly share code, notes, and snippets.

@reox
Created January 8, 2015 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reox/0fb5160c6c4ba2280714 to your computer and use it in GitHub Desktop.
Save reox/0fb5160c6c4ba2280714 to your computer and use it in GitHub Desktop.
Format seconds to human readable format
import time
def format_time(time):
m, s = divmod(time, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
# could be extended here to weeks, months, years, ...
# but the exact calculation of months, weeks and years is a little bit
# more difficult... so we leave it as it is.
out = []
fmt = lambda x: (x, "" if x == 1 else "s")
if d > 0:
out.append("%d day%s" % fmt(d))
if h > 0:
out.append("%d hour%s" % fmt(h))
if m > 0:
out.append("%d minute%s" % fmt(m))
if s > 0:
out.append("%d second%s" % fmt(s))
return " ".join(out)
print(format_time(time.time()))
# should print something like
# '16443 days 12 hours 52 minutes 49 seconds'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment