gpt4 book ai didi

python - 我怎么能实现 “HH:MM:SS” 格式

转载 作者:行者123 更新时间:2023-12-05 09:27:14 25 4
gpt4 key购买 nike

我被要求这样做:

编写一个程序,在给定小时、分钟和秒的情况下,将时钟时间加一秒。

输入由三个表示时钟时间的自然数h、m、s组成,即h<24,m<60,s<60。

这是我想出的代码:

from easyinput import read
h = read(int)
m = read(int)
s = read(int)

seconds = (s+1)%60
minutes = (m + (s+1)//60)%60
hours = h + (m + (s+1)//60))//60

print(hours, minutes, seconds)

如果有的话,它的功能很好

13 59 59

返回

14 0 0

我相信它可以改进,但这不是现在的问题。

问题是我需要这样的格式:

11:33:16

应该是“HH:MM:SS”,不知道怎么弄。任何人都可以帮助我??谢谢 :)))

最佳答案

使用带格式修饰符的 f 字符串。 02d 表示“一个字段宽度为 2 的 int,用 0 填充。”

print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
>>> hours = 13
>>> minutes = 3
>>> seconds = 5
>>> print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
13:03:05
>>>

请注意,格式说明符中的 d 是不必要的。你可以这样写:

print(f"{hours:02}:{minutes:02}:{seconds:02}")

Documentation on f-strings.

关于python - 我怎么能实现 “HH:MM:SS” 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72822147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com