How to convert float into Hours Minutes Seconds?

拟墨画扇 提交于 2020-01-22 03:33:09

问题


I've values in float and I am trying to convert them into Hours:Min:Seconds but I've failed. I've followed the following post:

Converting a float to hh:mm format

For example I've got a value in float format:

time=0.6 

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

and it gives me the output:

00:36 

But actually it should be like "00:00:36". How do I get this?


回答1:


Divmod function accepts only two parameter hence you get either of the two Divmod()

So you can try doing this:

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



回答2:


You're not obtaining the hours from anywhere so you'll first need to extract the hours, i.e.:

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

Then you can deal with formatting, i.e.:

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



回答3:


You can make use of the datetime module:

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


来源:https://stackoverflow.com/questions/51846547/how-to-convert-float-into-hours-minutes-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!