如果小時數為單個數字(04)或小時數為 24 小時格式,我想插入 0,則不應更改。我是 python 新手。請指導我。
current_time = '08:00'
lst = ['00:00','04:00','08:00','12:00','16:00','20:00']
if current_time in lst:
hour, minute = current_time.split(':')
if hour == '00':
hour = '24'
start_hour = int(hour)-4
start_time = str(start_hour) ':' '00'
end_hour = int(hour)-1
end_time = str(end_hour) ':' '59'
print(start_time,end_time)
我得到這樣的輸出:
4:00 7:59
但我期待這樣的輸出
04:00 07:59
我試過下面的方法
if len(start_time[0])==1:
start_time = start_time[:0] '0' start_time[0:]
output:
016:00
uj5u.com熱心網友回復:
這是使用zfill的方法:
current_time = '08:00'
lst = ['00:00','04:00','08:00','12:00','16:00','20:00']
if current_time in lst:
hour, minute = current_time.split(':')
if hour == '00':
hour = '24'
start_hour = int(hour)-4
start_time = str(start_hour).zfill(2) ':' '00'
end_hour = int(hour)-1
end_time = str(end_hour).zfill(2) ':' '59'
print(start_time,end_time)
結果:
04:00 07:59
uj5u.com熱心網友回復:
您可以嘗試使用 python f-strings,代碼如下
start_time = f'{start_hour:02d}:00'
end_time = f'{end_hour:02d}:00'
uj5u.com熱心網友回復:
Python中已經rjust(width, fillchar)內置了一個函式,它將為您的字串添加填充。只需更改start_time = str(start_hour) ':' '00'為start_time = str(start_hour).rjust(2, '0') ':' '00',它會在需要時添加缺失的零。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430672.html
