Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 580
Boosted_d16 Avatar asked Jan 05 '15 12:01

Boosted_d16


People also ask

How do you format elapsed time in Python?

Formatting the Elapsed Time of Program in Python We can use the timedelta() function from the datetime module to create a timedelta object which will format the time elapsed. When printed to the console, timedelta objects print HH:MM:SS.

How do I display hours minutes and seconds in Python?

Use the divmod() Function to Convert Seconds Into Hours, Minutes, and Seconds in Python. The divmod() function can convert seconds into hours, minutes, and seconds. The divmod() accepts two integers as parameters and returns a tuple containing the quotient and remainder of their division.

How do you convert seconds to HH MM SS?

To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds.


3 Answers

You could exploit timedelta:

>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'
like image 59
jfs Avatar answered Oct 22 '22 07:10

jfs


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 [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.19
In [14]: timer(12300.242,12600.5452)
00:05:00.30
In [19]: timer(0.343,86500.8743)
24:01:40.53
In [16]: timer(0.343,865000.8743)
 240:16:40.53    
In [17]: timer(0,0.232999801636)
00:00:00.23
like image 33
Padraic Cunningham Avatar answered Oct 22 '22 08:10

Padraic Cunningham


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

elapsed = 4*3600 + 13*60 + 6                       # 15186 s
time.strftime("%Hh%Mm%Ss", time.gmtime(elapsed))   # '04h13m06s'
like image 5
Friedrich Avatar answered Oct 22 '22 07:10

Friedrich