Converting milliseconds to human amount of time
Rocco Moretti
roccomoretti at hotpop.com
Mon Jan 9 10:30:07 EST 2006
Max wrote:
> Harlin Seritt wrote:
>
>> How can I take a time given in milliseconds (I am doing this for an
>> uptime script) and convert it to human-friendly time i.e. "4 days, 2
>> hours, 25 minutes, 10 seonds."? Is there a function from the time
>> module that can do this?
>>
>> Thanks,
>>
>> Harlin Seritt
>>
>
> seconds = millis / 1000 # obviously
>
> minutes = seconds / 60
> seconds %= 60
>
> hours = minutes / 60
> minutes %= 60
>
> days = hours / 24
> hours %= 24
>
> All this using integer division, of course. This is probably much more
> verbose than the tersest soln, but it works (or should do - I haven't
> tested it). It's not strictly accurate (from a scientific/UTC
> perspective, as some minutes have 59 or 61 seconds rather than 60, but
> it's probably the best you need.
You'd probably be helped by divmod:
>>> help(divmod)
Help on built-in function divmod in module __builtin__:
divmod(...)
divmod(x, y) -> (div, mod)
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
>>> def humanize(milli):
sec, milli = divmod(milli, 1000)
min, sec = divmod(sec, 60)
hour, min = divmod(min, 60)
day, hour = divmod(hour, 24)
week, day = divmod(day, 7)
print week, "weeks,", day, "days,", hour, "hours,", \
min, "minutes,", sec, "seconds, and", \
milli, "milliseconds"
return (week, day, hour, min, sec, milli)
>>> humanize(1234567890)
2 weeks, 0 days, 6 hours, 56 minutes, 7 seconds, and 890 milliseconds
(2, 0, 6, 56, 7, 890)
>>> humanize(694861001.1) #Also works with floats!
1.0 weeks, 1.0 days, 1.0 hours, 1.0 minutes, 1.0 seconds, and
1.10000002384 milliseconds
(1.0, 1.0, 1.0, 1.0, 1.0, 1.1000000238418579)
More information about the Python-list
mailing list