How to convert time seconds to h:m:s format in Python?

PythonServer Side ProgrammingProgramming

If you have a function that returns information in seconds, but you need that information in hours:minutes:seconds format, you can use 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:

Example

seconds = 56741
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print "%d:%02d:%02d" % (h, m, s)

Output

This will give the output −

15:45:41

You can also use the timedelta function to get the same functionality but at a cost to performance. 

example

import datetime
timedelta_obj = datetime.timedelta(seconds=56741)
print(timedelta_obj)

Output

This will give the output −

15:45:41
raja
Published on 08-Jan-2018 12:03:38
Advertisements