我该如何将经过的时间从秒转换为小时、分钟和秒?
我的代码:
start = time.time()
... do something
elapsed = (time.time() - start)
实际输出:
0.232999801636
期望输出:
00:00:00.23
您可以利用timedelta
对象:
>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'
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
str(datetime.timedelta(seconds=(stop-start)))
https://dev59.com/aV4c5IYBdhLWcg3wjrDR#27793118 - Steven C. Howellimport 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))
temp = 65432
进行了测试,因此我无法看到仅工作几秒钟的输出将缺少双零。@PadraicCunningham - implicati0nprint("Elapsed time: " + time.strftime("%H:%M:%S.{}".format(str(elapsed % 1)[2:])[:15], time.gmtime(elapsed)))
输出:
Elapsed time: 00:38:01.357318
Elapsed time: 00:45:18.65
str(timedelta(seconds=86401))
->'1天,0:00:01'
- jfs