gpt4 book ai didi

python - 如何给时间加零

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:47 26 4
gpt4 key购买 nike

我有一个函数,它接收字符串形式的时间以及要添加到时间中的另一个数字:

def get_hours(hm):
return int(hm.split(':')[0])

def get_minutes(hm):
return int(hm.split(':')[1])


def add_minutes(hm, incr):
"""Increment the given time by the given amount of minutes.

Requires:
- hm str with a time represented as HH:MM;
- incr int with the number of minutes.
Ensures: str with a time represented as HH:MM, the result of incrementing hm by incr minutes.
"""
if get_minutes(hm)+incr>=60:
if get_hours(hm)==23:
return '00:'+str((get_minutes(hm)+incr)-60)
else:
return str(get_hours(hm)+1)+':'+str((get_minutes(hm)+incr)-60)
else:
return str(get_hours(hm))+':'+str((get_minutes(hm)+incr))

问题是当时间为 16:05 或 04:06 时,它不显示零,因此只有 16:5 和 4:6。我怎样才能做到这一点?

最佳答案

Python 在字符串类上有一个函数可以帮助您;

"3".zfill(2)  # this will output 03
"20".zfill(2) # this will output 20

只需将整数转换为字符串,并在打印任何结果之前调用 .zfill(2) 即可。

关于python - 如何给时间加零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47644135/

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