在Python中将时间从AM/PM格式转换为24小时制

6

我正在尝试解决Hackerrank问题 "时间转换", 以下是该问题的陈述,不使用任何库。

enter image description here

我想到了以下内容:

time = raw_input().strip()

meridian = time[-2:]        # "AM" or "PM"
time_without_meridian = time[:-2]
hour = int(time[:2])

if meridian == "AM":
    hour = (hour+1) % 12 - 1
    print ("%02d" % hour) + time_without_meridian[2:]
elif meridian == "PM":
    hour += 12
    print str(hour) + time_without_meridian[2:]

然而,这在一个测试用例上失败了:

enter image description here

由于测试用例对用户隐藏,因此我很难看出问题出在哪里。 "12:00:00AM" 被正确地转换为 "00:00:00",而 "01:00:00AM" 被转换为 "01:00:00"(带有填充零)。这个实现可能存在什么问题?

这是一个好问题,请手动输入图像文本。另外我有一个类似的相关问题,关于在re.sub的repl表达式中不能调用捕获组的函数?例如 int(r'\1')。 (https://stackoverflow.com/questions/57128923/cant-call-a-function-on-capture-group-in-the-repl-expression-of-re-sub-e-g-in?noredirect=1) - smci
由于您的代码正确实现,'12'是一个特殊情况:'12PM'不会转换为12+12=24,而'12AM'确实会转换为'00'。但是,像@selbie一样处理hour==12的特殊情况比使用扭曲的hour = (hour+1) % 12 - 1更简单。 - smci
5个回答

9

你已经解决了问题,但这里还有另一个可能的答案:

from datetime import datetime


def solution(time):
    return datetime.strptime(time, '%I:%M:%S%p').strftime('%H:%M:%S')


if __name__ == '__main__':
    tests = [
        "12:00:00PM",
        "12:00:00AM",
        "07:05:45PM"
    ]
    for t in tests:
        print solution(t)

尽管这将使用Python库 :-)

9
比你现有的方法还要简单。
hour = int(time[:2])
meridian = time[8:]
# Special-case '12AM' -> 0, '12PM' -> 12 (not 24)
if (hour == 12):
    hour = 0
if (meridian == 'PM'):
    hour += 12
print("%02d" % hour + time[2:8])

如果您解释“12”是一个特殊情况会有所帮助:“12PM”不会转换为12 + 12 = 24,而“12AM”确实会转换为“00”。 - smci

3
from datetime import datetime

#Note the leading zero in 05 below, which is required for the formats used below

regular_time = input("Enter a regular time in 05:48 PM format: ")

#%I is for regular time. %H is for 24 hr time, aka "military time"
#%p is for AM/PM

military_time = datetime.strptime(regtime, '%I:%M %p').strftime('%H:%M')

print(f"regular time is: {regular_time"}
print(f"militarytime is {military_time}")

以下链接被证明非常有用:https://strftime.org/

1
我明白了:它将“12:00:00PM”转换为“24:00:00”,而不是“12:00:00”。我按以下方式修改了代码:
time = raw_input().strip()

meridian = time[-2:]        # "AM" or "PM"
time_without_meridian = time[:-2]
hour = int(time[:2])

if meridian == "AM":
    hour = (hour+1) % 12 - 1
    print ("%02d" % hour) + time_without_meridian[2:]
elif meridian == "PM":
    hour = hour % 12 + 12
    print str(hour) + time_without_meridian[2:]

导致它通过了所有的测试用例(见下文)。

enter image description here


0
dt_m = datetime.datetime.fromtimestamp(m_time)
hour_m = (dt_m.hour%12)+1  #dt_m.hour+1
offset_dt = datetime.datetime(dt_m.year, dt_m.month, dt_m.day, hour_m , dt_m.minute, dt_m.second, dt_m.microsecond)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接