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

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


You could exploit timedelta:

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


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

import timestart = 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 [12]: 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 [13]: timer(12345.242,12356.434)00:00:11.19In [14]: timer(12300.242,12600.5452)00:05:00.30In [19]: timer(0.343,86500.8743)24:01:40.53In [16]: timer(0.343,865000.8743) 240:16:40.53    In [17]: timer(0,0.232999801636)00:00:00.23


The strftime function of time itself can be (ab)used with limitations (no millisec and <24 hr)

elapsed = 4*3600 + 13*60 + 6                       # 15186 stime.strftime("%Hh%Mm%Ss", time.gmtime(elapsed))   # '04h13m06s'