Created
January 8, 2015 12:54
-
-
Save reox/0fb5160c6c4ba2280714 to your computer and use it in GitHub Desktop.
Format seconds to human readable format
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
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