在Python中将十进制时间(HH.HHH)转换为HH:MM:SS [英] Converting decimal time (HH.HHH) into HH:MM:SS in Python
问题描述
我有这种格式的小时数,
I have hours in this format,
72.345, 72.629, 71.327, ...
在Python中执行计算的结果。似乎将它们转换为HH:MM:SS格式的最简单方法是使用datetime模块,如下所示:
as a result of performing a calculation in Python. It seems that the simplest way to convert these into HH:MM:SS format is using the datetime module like this:
time = str(datetime.timedelta(seconds = 72.345*3600))
但是,返回的值是天,我不希望这样做:
However, that returns a values with days, which I don't want:
'3 days, 0:20:42'
这是我的大脑得出我想要的最终值的最佳方法:
This is the best way my brain came up with the final values I want:
str(int(math.floor(time))) + ':' + str(int((time%(math.floor(time)))*60)) + ':' + str(int(((time%(math.floor(time)))*60) % math.floor(((time%(math.floor(time)))*60))*60))
这太长了,可能没有必要。但这确实给了我想要的答案:
Which is ridiculously long and probably unnecessary. But it does give me the answer I want:
'72:20:41'
还有更好的方法吗?
推荐答案
您不必使用 datetime
。您可以轻松地从小数点开始计算小时,分钟和秒。
You do not have to use datetime
. You can easily compute hours, minutes and seconds from your decimal time.
您还应该注意,可以使用字符串格式,它比字符串串联更容易使用。 / p>
You should also notice that you can use string formatting which is really easier to use than string concatenation.
time = 72.345
hours = int(time)
minutes = (time*60) % 60
seconds = (time*3600) % 60
print("%d:%02d.%02d" % (hours, minutes, seconds))
>> 72:20:42
这篇关于在Python中将十进制时间(HH.HHH)转换为HH:MM:SS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!