CheckIO是一个通过闯关游戏学习编程的网站(Python和JavaScript)。通过解题开发新“岛屿”,同时,通过做任务获得Quest Points解锁会员题目。
文章内容:题目、我自己的思路和代码以及优秀代码,如果想看大神解题可以直接跳到“优秀代码”部分。
本题链接:https://py.checkio.org/en/mission/time-converter-12h-to-24h/
题目
作为现代人,我们更习惯24小时制,但是一些情况下依然会使用12小时制。这一任务是要将12小时制转换为24小时制,注意:
- 输出格式为:
'hh:mm'
- 如果输出时间的小时小于
10
,在数字前填'0'
,例如:'09:05'
这一任务中,能了解更多关于12小时制的信息
输入: 12小时制的时间(字符串格式)
输出: 24小时制的时间(字符串格式)
举个栗子:
time_converter('12:30 p.m.') == '12:30'
time_converter('9:00 a.m.') == '09:00'
time_converter('11:15 p.m.') == '23:15'
用处: 统一时间格式
假设: '00:00' <= 时间 <= '23:59'
题目框架
def time_converter(time):
# Your code here!
return time
if __name__ == '__main__':
print("Example:")
print(time_converter('12:30 p.m.'))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert time_converter('12:30 p.m.') == '12:30'
assert time_converter('9:00 a.m.') == '09:00'
assert time_converter('11:15 p.m.') == '23:15'
print("Coding complete? Click 'Check' to earn cool rewards!")
难度: Simple
思路及代码
思路
- 找到时间中间的
:
,记录小时hour
; - 用
converter_hour
保存转换后的hour
的字符形式; - 判断时间,如果是上午还是下午;
- 如果是下午:
hour < 12
时,converter_hour = str(hour + 12)
;hour = 12
时,converter_hour = str(hour)
; - 如果是上午:
time == '12:00 a.m.'
时,converter_hour = '00'
;hour < 10
时,converter_hour = str(0) + str(hour)
;其他情况,converter_hour = str(hour)
代码
def time_converter(time):
index = time.find(':')
hour = int(time[:index])
if time[-4:] == 'p.m.':
if hour < 12:
converter_hour = str(hour + 12)
else:
converter_hour = str(hour)
else:
if time == '12:00 a.m.':
converter_hour = '00'
elif hour < 10:
converter_hour = str(0) + str(hour)
else:
converter_hour = str(hour)
return converter_hour + time[index:index+3]
优秀代码
No.1
def time_converter(time):
h, m = map(int, time[:-5].split(':'))
return f"{h % 12 + 12 * ('p' in time):02d}:{m:02d}"
大神的解释:
def time_converter(time):
# h, m = map(int, time[:-5].split(':'))
splited_time = time[:-5].split(':') # splited_time == "12:30".split(':') == ["12", "30"]
h = int(splited_time[0]) # h = int("12")
m = int(splited_time[1]) # h = int("34")
# return f"{h % 12 + 12 * ('p' in time):02d}:{m:02d}"
# 1. hour = h % 12 + 12 * ('p' in time)
hour = h
if h == 12: # h % 12 part
hour = 0 # this means conversion from "12:30 p.m." to "00:30 p.m."
if 'p' in time: # + 12 * ('p' in time) part
hour += 12 # when PM, add 12 hours
else:
hour += 0 # when AM, add 0 hours
# 2. return f"..."
result = "{:02d}:{:02d}".format(hour, m)
return result
No.2
import time
def time_converter(now):
return time.strftime('%H:%M', time.strptime(now.replace('.', ''), '%I:%M %p'))
No.3
def time_converter(str_time):
time, am_pm = str_time.split()
hour, minute = map(int, time.split(':'))
hour = hour % 12 + 12*(am_pm == 'p.m.')
return f'{hour:02}:{minute:02}'