我在完成任务时遇到困难。该任务要求用户输入时间(1 到 12 之间),然后声明是上午还是下午,以及将其转发到多少小时。转发的时间还应该显示上午/ pm 时间戳取决于转发的数量。示例:Input time: 8am or pm : amforward: 5new time: 1pm我已经尝试过这个: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贡献1785条经验 获得超8个赞
我建议简单地将时间转换为 24 小时格式,转发,然后转换回 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
提交
取消