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

时间:2015-01-05 12:36:30

标签: python time format elapsed

如何格式化从秒到小时,分钟,秒的时间?

我的代码:

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

实际输出:

0.232999801636

期望/预期输出:

00:00:00.23 

4 个答案:

答案 0 :(得分:91)

您可以利用timedelta

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

答案 1 :(得分:27)

如果您希望在输入中加入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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

time本身的strftime功能可以(有限制)使用(no millisec和<24小时)

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