我在完成任務(wù)時遇到困難。該任務(wù)要求用戶輸入時間(1 到 12 之間),然后聲明是上午還是下午,以及將其轉(zhuǎn)發(fā)到多少小時。轉(zhuǎn)發(fā)的時間還應(yīng)該顯示上午/ pm 時間戳取決于轉(zhuǎn)發(fā)的數(shù)量。示例:Input time: 8am or pm : amforward: 5new time: 1pm我已經(jīng)嘗試過這個:time = eval(input('Input time(1-12):'))ampm = eval(input('am or pm?'))forward = eval(input('Forward:'))if ampm == am: if time + forward > 24: new time = (time + forward)%24 x = 'am' else: new time = (time + forward)%12 x = 'pm' print('New time is:' , new time , x)if ampm == pm: if time + forward > 12: new time = (time + forward)%12 x = 'pm' else: new time = (time + forward)%24 x = 'am' print('New time is:' , new time , x)
1 回答

慕的地10843
TA貢獻(xiàn)1785條經(jīng)驗 獲得超8個贊
我建議簡單地將時間轉(zhuǎn)換為 24 小時格式,轉(zhuǎn)發(fā),然后轉(zhuǎn)換回 12 小時(上午/下午)格式。
我是這樣做的:
time = int(input('Input time(1-12):'))
ampm = input('am or pm?')
forward = int(input('Forward:'))
# first get the 24h formatted time
time_24 = time + 12 if ampm == 'pm' else time
# then forward time to max 24, else start over from 0
time_24 = (time_24 + forward) % 24
# finally convert back to 12h(am/pm) format
time_12 = f'{time_24-12}pm' if time_24 > 12 else f'{time_24}am'
# print out the forwarded time
print(time_12)
添加回答
舉報
0/150
提交
取消