Python 将浮点数转换为 hh:mm 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27496889/
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
Converting a float to hh:mm format
提问by Liam Rahav
I want to print a float value that I've got after performing some math as time string in the hh:mm format. Currently I have the float like 9.888888888888886 and I want it in time like 09:50. I have tried the following code:
我想打印一个浮点值,该值是在以 hh:mm 格式执行一些数学运算后作为时间字符串获得的。目前我有像 9.888888888888886 这样的浮点数,我想要它像 09:50 这样的时间。我尝试了以下代码:
time = str(time)
time = time.split(".")
time[1] = float(time[1])
time[1] *= 0.6
time[1] = str(time[1])
and when I print I use
当我打印时,我使用
str(time[0]) + ":" + time[1][:2]
Any way to achieve this effect consistently? With more advanced inputs my above code does not work properly, and outputs the wrong time.
有什么方法可以始终如一地达到这种效果?使用更高级的输入,我上面的代码无法正常工作,并输出错误的时间。
采纳答案by Jon Clements
Alternatively to using datetime
, you can just use simple formatting with a bit of maths, eg:
可选择使用datetime
,你可以用简单的格式有位数学,例如:
result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60))
回答by falsetru
Using datetime.timedelta
:
>>> import datetime
>>> datetime.timedelta(hours=9.888888888888886)
datetime.timedelta(0, 35600)
>>> str(datetime.timedelta(hours=9.888888888888886))
'9:53:20'
>>> str(datetime.timedelta(hours=9.888888888888886)).rsplit(':', 1)[0]
'9:53'
>>> datetime.datetime.combine(datetime.date.today(), datetime.time()) + \
... datetime.timedelta(hours=9.888888888888886)
datetime.datetime(2014, 12, 16, 9, 53, 20)
>>> _.strftime('%H:%M')
'09:53'
回答by Gagravarr
Assuming you want to turn 9.888888888888886
into 09:53
, based on the former being floating point hours, and you don't want to worry about days, without a library you could simply do:
假设你想9.888888888888886
变成09:53
,基于前者是浮点小时,并且你不想担心几天,没有图书馆你可以简单地做:
fhours = 9.888888888888886
ihours = int(ihours)
"%02d:%02d" % (ihours,(fhours-ihours)*60)
With only the math module, try
只有数学模块,尝试
import math
"%02d:%02d" % (fhours,math.modf(fhours)[0]*60)
You might think that using the datetime
module would help, but it's actually a bit fiddly. You can get a timedelta object out by passing in your fractional hours:
您可能认为使用该datetime
模块会有所帮助,但实际上它有点繁琐。您可以通过传入小数小时来获取 timedelta 对象:
import datetime
td = datetime.timedelta(hours=9.888888888888886)
But getting that into a time object or a datetime object to format is the tricky bit, you end up having to do something like
但是将它放入时间对象或日期时间对象进行格式化是一个棘手的问题,你最终不得不做一些类似的事情
import datetime
td = datetime.timedelta(hours=9.888888888888886)
(datetime.datetime(2000,1,1)+td).strftime("%H:%M")
(That uses a randomly picked date to get the time delta into a datetime to use)
(使用随机选择的日期将时间增量转换为要使用的日期时间)
回答by f.rodrigues
Using divmod you get the remainder and the quotient of a division.
使用 divmod 可以获得除法的余数和商。
minutes = 9.888888888888886*60
hours, minutes = divmod(minutes, 60)
print "%02d:%02d"%(hours,minutes)
Output:
输出:
09:53
If you want the seconds too:
如果你也想要秒数:
seconds = 9.888888888888886*60*60
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print "%02d:%02d:%02d"%(hours,minutes,seconds)
回答by ZF007
For python 3.7 version this becomes an one-liner.
对于 python 3.7 版本,这变成了单行。
x = 9.888888888888886
print (str(datetime.timedelta(hours=x))[:-3])
(Here the time-string minus the last three chars is printed.)
(这里打印了减去最后三个字符的时间字符串。)
Result 1 : 9:53
结果 1 : 9:53
Alternatively if you needs seconds:
或者,如果您需要几秒钟:
print (datetime.timedelta(hours=x))
print (datetime.timedelta(hours=x))
Result 2 : 9:53:20
结果 2 : 9:53:20
And finally if you go beyond the 24hour mark timedelta shows the added day as well:
最后,如果您超出 24 小时标记 timedelta 也会显示添加的日期:
x = 39.888888888888886
x = 39.888888888888886
Result 3 : 1 day, 15:53:20
结果 3 : 1 天, 15:53:20