This question is similar to this question about subtracting dates with Python, but not identical. I\'m not dealing with strings, I have to figure out the difference between
Old question, but I personally like this approach most:
import datetime
import math
def human_time(*args, **kwargs):
secs = float(datetime.timedelta(*args, **kwargs).total_seconds())
units = [("day", 86400), ("hour", 3600), ("minute", 60), ("second", 1)]
parts = []
for unit, mul in units:
if secs / mul >= 1 or mul == 1:
if mul > 1:
n = int(math.floor(secs / mul))
secs -= n * mul
else:
n = secs if secs != int(secs) else int(secs)
parts.append("%s %s%s" % (n, unit, "" if n == 1 else "s"))
return ", ".join(parts)
human_time(seconds=3721)
# -> "1 hour, 2 minutes, 1 second"
If you want to separate the seconds part with an "and" do:
"%s and %s" % tuple(human_time(seconds=3721).rsplit(", ", 1))
# -> "1 hour, 2 minutes and 1 second"