python - 在 Python 中将时间从 AM/PM 格式转换为军事时间

标签 python

在不使用任何库的情况下,我正在尝试解决 Hackerrank 问题“Time Conversion”,其问题陈述复制如下。

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”(填充零)。此实现可能有什么问题?

最佳答案

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

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 库 :-)

关于python - 在 Python 中将时间从 AM/PM 格式转换为军事时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184198/

相关文章:

python - 如何在 ruby​​ 中进行图像处理? Ruby 中没有 OpenCv?

python - 从 python 异常中杀死 Bash 脚本

python - 将 pandas 数据框列拆分为多个 bool 列

python - 按 VPC ID 列出 AWS 中的子网

python - 在 python 中过滤/迭代非常大的列表

python标准输入eof

python - 使用 RecycleView 时设置列宽

python - 如何为 Altair 生成的图表添加副标题

python - Python 字典可以作为 Neo4j 文字映射传递吗?

Java:将简单操作从 Python 移植到 Java/列表处理