O‘REILLY: Time Converter —— 12小时制转24小时制

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小时制的信息
O‘REILLY: Time Converter —— 12小时制转24小时制
输入: 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

思路及代码

思路

  1. 找到时间中间的 :,记录小时 hour
  2. converter_hour 保存转换后的 hour 的字符形式;
  3. 判断时间,如果是上午还是下午;
  4. 如果是下午:hour < 12 时,converter_hour = str(hour + 12)hour = 12 时,converter_hour = str(hour)
  5. 如果是上午: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}'
上一篇:**##根据结束时间与系统时间形成倒计时时间差*************


下一篇:MySQL自动备份和手工恢复(可实现定时备份、保留最近7天、异地备份)