将存储在元组中的 'time values' 转换为 24 小时格式

Converting 'time values' stored in a tuple into 24 hours format

假设您有一个元组(小时、分钟)并且您希望将其转换为 24 小时格式 hh:mm:ss。假设秒将始终为 0。例如。 (14,0) 将是 14:00:00 而 (15,0) 将是 15:00:00.

到目前为止,这是我接近答案的粗略方式:

start_time = (14, 0)
st = ''

for num in start_time:
num = str(num)
if len(num) == 2:
    st += num
else:
    
    st += str(num) + '00'
print(st)

您当前方法存在的问题:

  • 您没有使用任何 : 字符。每次迭代后,通过考虑 for 循环中的索引来检查它是否是最后一次。如果不是,请附加一个 : 字符。

  • 如果 len(num) == 1,你插入了两个尾随零,而它应该是一个前导零。

重构代码:

start_time = (14, 0)
st = ''

# `i` will store the index for each iteration
for i, num in enumerate(start_time):
    num = str(num)

    if len(num) == 2:
        st += num
    else:
        # If the number of digits is not 2, append a leading '0'
        st += '0' + num
        
    # If it's not the last number in the tuple
    if i < len(start_time) - 1:
        st += ':'
    else:
        st += ':00'
        
print(st)

这将输出预期值。

另一种简洁的方法:

def time(t):
    #      vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv   Join the mapped values to a single string using `:`
    #               vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv    Map this function to each value in this new tuple
    #                   vvvvvvvvvvvvvvv               Create a function that adds two trailing zero to a value
    #                                    vvvvvvvv     Create a new tuple with a trailing zero
    return ':'.join(map('{:02d}'.format, t + (0,)))

print(time((14, 0)))
print(time((15, 0)))

我知道您可能只是在训练字符串,但如果您想创建合适的日期时间对象,请使用日期时间模块:

from datetime import datetime

def create_time(x: tuple):
    return datetime.strptime(f"2021-11-03 {x[0]}:{x[1]}", "%Y-%m-%d %H:%M")
                            #   ^^^^^^^^ you can set the date if needed
print(create_time((14, 15)))

输出:

2021-11-03 14:15:00

如果您只需要时间,只需使用 .time() 方法:

from datetime import datetime

def create_time(x: tuple):
    return datetime.strptime(f"{x[0]}:{x[1]}", "%H:%M").time()
print(create_time((14, 15)))

输出:

14:15:00