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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27779677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:15:25  来源:igfitidea点击:

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

pythontimeformatelapsed

提问by Boosted_d16

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 

采纳答案by Padraic Cunningham

If you want to include times like 0.232999801636as in your input:

如果您想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))

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

回答by implicati0n

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

回答by jfs

You could exploit timedelta:

你可以利用timedelta

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