Converting milliseconds to human amount of time

H

Harlin Seritt

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
 
M

Max

Harlin said:
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.

--Max
 
R

Rocco Moretti

Max said:
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 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.
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)
2 weeks, 0 days, 6 hours, 56 minutes, 7 seconds, and 890 milliseconds
(2, 0, 6, 56, 7, 890)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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top