90

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 
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Boosted_d16
  • 13,340
  • 35
  • 98
  • 158

5 Answers5

203

You could exploit timedelta:

>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'
pixelou
  • 748
  • 6
  • 17
jfs
  • 399,953
  • 195
  • 994
  • 1,670
84

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
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    This is a great demonstration of the overall idea, maybe good for a customized formatting, but for simply showing a formatted version of the elapsed time, the solution from jfs is probably more clear with less technical overhead: `str(datetime.timedelta(seconds=(stop-start)))` https://stackoverflow.com/a/27793118/3585557 – Steven C. Howell Mar 16 '21 at 18:08
11

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'
3
import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))
implicati0n
  • 269
  • 2
  • 10
  • I tested it by setting `temp = 65432` so I couldn't see that the output for something that works just a few seconds will be missing the double zeros. @PadraicCunningham – implicati0n Jan 05 '15 at 13:35
3

If you want one line of code without import any other library, that worked for me (Python v3.7.11):

print("Elapsed time: " + time.strftime("%H:%M:%S.{}".format(str(elapsed % 1)[2:])[:15], time.gmtime(elapsed)))

Output:

Elapsed time: 00:38:01.357318

You can control the milliseconds to be displayed by modifying "[:15]" to "[:11]", then you will get the desired result:

Elapsed time: 00:45:18.65
César L.
  • 31
  • 2