How do I convert seconds to hours, minutes and seconds?


Question

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.

Is there an easy way to convert the seconds to this format in Python?

1
402
10/29/2018 11:35:24 PM

Accepted Answer

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
638
2/5/2019 6:31:55 PM

By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)

And then use string formatting to convert the result into your desired output:

print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon