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

Boosted_d16 picture Boosted_d16 · Jan 5, 2015 · Viewed 56.3k times · Source

How can I format the time elapsed from seconds to hours, mins, seconds?

My code:

start = time.time()
... do something
elapsed = (time.time() - start)

Actual Output:

0.232999801636

Desired/Expected output:

00:00:00.23 

Answer

jfs picture jfs · Jan 6, 2015

You could exploit timedelta:

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