How to convert seconds to HH:MM:SS format without failing if hour more than 24

Viewed 1067

I need to convert seconds to HH:MM:SS format without failing if hour greater than 24hrs.

Such as 04:32:18 or 26:23:37

Here's what I tried:

import time

cd = time.time()

while True:
    # Count seconds
    te = int(time.time()-cd, 0)

    # Print the secs
    print('Time elapsed:', te, 'secs')
    time.sleep(1)

This code prints this result:

Time elapsed 1.0 secs
Time elapsed 2.0 secs
...

But I want this result:

Time elapsed 00:00:01 secs
Time elapsed 00:00:02 secs
...

And if the hour greater than 24, the program must run and print something like:

Time elapsed: 28:34:35
Time elapsed: 28:34:36
...

Hope you help.

1 Answers

you can easily decompose your seconds in h, m, s with divmod

def to_hms(s):
    m, s = divmod(s, 60)
    h, m = divmod(m, 60)
    return '{}:{:0>2}:{:0>2}'.format(h, m, s)
>>> to_hms(90127)
'25:02:07'
Related