将浮点数转换为hh:mm格式 [英] Converting a float to hh:mm format

查看:77
本文介绍了将浮点数转换为hh:mm格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以hh:mm格式以时间字符串形式打印经过数学运算后得到的浮点值。目前,我有9.888888888888886之类的浮动货币,我想按09:50之类的时间发布。我尝试了以下代码:

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:

    time = str(time)
    time = time.split(".")
    time[1] = float(time[1])
    time[1] *= 0.6
    time[1] = str(time[1])

打印时我使用

    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.

推荐答案

或者使用 datetime ,您可以使用带有一些数学运算的简单格式,例如:

Alternatively to using datetime, you can just use simple formatting with a bit of maths, eg:

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

这篇关于将浮点数转换为hh:mm格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆