如何将 float 转换为时分秒?

How to convert float into Hours Minutes Seconds?

我有浮点值,我试图将它们转换为 Hours:Min:Seconds,但我失败了。我关注了以下 post:

Converting a float to hh:mm format

例如我有一个浮点格式的值:

time=0.6 

result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60))

它给了我输出:

00:36 

但实际上应该是“00:00:36”。我如何获得这个?

Divmod 函数只接受两个参数,因此您可以得到这两个参数中的一个 Divmod()

所以你可以尝试这样做:

time = 0.6
mon, sec = divmod(time, 60)
hr, mon = divmod(mon, 60)
print "%d:%02d:%02d" % (hr, mon, sec)

您无法从任何地方获取小时数,因此您首先需要提取小时数,即:

float_time = 0.6  # in minutes
hours, seconds = divmod(float_time * 60, 3600)  # split to hours and seconds
minutes, seconds = divmod(seconds, 60)  # split the seconds to minutes and seconds

然后就可以处理格式化了,即:

result = "{:02.0f}:{:02.0f}:{:02.0f}".format(hours, minutes, seconds)
# 00:00:36

您可以使用日期时间模块:

import datetime
time = 0.6
result = str(datetime.timedelta(minutes=time))