web-dev-qa-db-fra.com

Comment formater le temps écoulé de secondes en heures, minutes, secondes et millisecondes en Python?

Comment formater le temps écoulé de secondes en heures, minutes, secondes? 

Mon code:

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

Sortie réelle:

0.232999801636

Résultat souhaité/attendu:

00:00:00.23 
20
Boosted_d16

Si vous souhaitez inclure des heures telles que 0.232999801636 dans votre saisie:

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))

Exemple:

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
24
Padraic Cunningham

Vous pourriez exploiter timedelta :

>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'
85
jfs
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))
0
implicati0n