How to format elapsed time from seconds to hours, minutes, seconds and milliseconds in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to format elapsed time from seconds to hours, minutes, seconds and milliseconds in Python in Python. So Here I am Explain to you all the possible Methods here.

How to format elapsed time from seconds to hours, minutes, seconds and milliseconds in Python?

1. How to format elapsed time from seconds to hours, minutes, seconds and milliseconds in Python?

If you want to include times like 0.232999801636 as in your input:
import time start = time.time() end = time.time() hours, rem = divmod(end-start, 3600)

2. format elapsed time from seconds to hours, minutes, seconds and milliseconds in Python

If you want to include times like 0.232999801636 as in your input:
import time start = time.time() end = time.time() hours, rem = divmod(end-start, 3600)

Method 1

You could exploit timedelta:

>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'

Method 2

If you want to include times like 0.232999801636 as in your input:

import time
start = time.time()
end = time.time()
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

Example:

In : def timer(start,end):
....:         hours, rem = divmod(end-start, 3600)
....:         minutes, seconds = divmod(rem, 60)
....:         print("{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
....:

In : timer(12345.242,12356.434)
00:00:11.19
In : timer(12300.242,12600.5452)
00:05:00.30
In : timer(0.343,86500.8743)
24:01:40.53
In : timer(0.343,865000.8743)
240:16:40.53
In : timer(0,0.232999801636)
00:00:00.23

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.