如何在 Python 中将经过的时间从秒格式化为小时、分钟、秒和毫秒?

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

如何将经过的时间从秒格式化为小时、分钟、秒?

我的代码:

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

实际输出:

0.232999801636

Desired/Expected 输出:

00:00:00.23 
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.232999801636 这样的时间:

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

示例:

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

您可以利用 timedelta:

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

strftime function of time itself can be (ab)used with limitations (no millisec 和 <24 小时)

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

如果你想要一行代码而不导入任何其他库,那对我有用(Python v3.7.11):

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

输出:

Elapsed time: 00:38:01.357318

你可以通过修改“[:15]”为“[:11]”来控制显示的毫秒数,然后你会得到想要的结果:

Elapsed time: 00:45:18.65