Python3.x : Format Float to 2 Digits, 限制为小数点后 3 位

标签 python time floating-point format

我见过很多关于格式化float和限制小数位数的问题,但我还没有看到这两个问题同时完成。我希望变量 seconds 的值始终表示为 SS.mmm。

我有

t = int(input('time?: '))
seconds = (t / 1000) % 60
minutes = (t // (1000 * 60)) % 60
hours = (t // (1000 * 60 * 60)) % 24

我想打印小时分钟,以便它始终遵循 HH:MM :SS.mmm

我的尝试:

print('{}:{}:{}'.format("%02d" % hours, "%02d" % minutes, ("%.3f" % seconds).zfill(2)))

有时我最终会得到 HH:MM:S.mmm。即使有前导零,我也需要有两秒数字。

最佳答案

您应该能够使用 .format() 执行以下操作:

print('{:0>2d}:{:0>2d}:{:06.3f}'.format(hours,minutes,seconds))

特别是,0>2d 强制整数小时分钟 的长度为2。此外,06.3f 意味着整个浮点表示形式应为 6 个字符长(包括 '.'),并且句点右侧有 3 个小数位。

关于Python3.x : Format Float to 2 Digits, 限制为小数点后 3 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45448187/

相关文章:

Python SQLite - 缓慢的更新记录

python - 初始化字符串数据的numpy数组的奇怪行为

python - Tornado :来自迭代器的 AsyncHttpClient.fetch?

c - 如何在 C 中获取十六进制日期和时间

c - C 中的四舍五入 float

c# - 小数的 N 次根在 C# 中返回意外结果

python - Pandas:子索引数据框:副本与 View

javascript - 如何使用 javascript 在定义的时间延迟后动态更改 <p> 标记数据?

r - 将日期和时间转换为日期+时间戳

python-3.x - 如何将数据类型更改为 float64 以便 sklearn 可以在数据大于 np.float32 的数据帧上工作