【发布时间】:2013-10-14 06:47:57
【问题描述】:
我正在尝试将时间从 12 小时时间转换为 24 小时时间......
自动示例时间:
06:35 ## Morning
11:35 ## Morning (If m2 is anywhere between 10:00 and 12:00 (morning to mid-day) during the times of 10:00 and 13:00 (1pm) then the m2 time is a morning time)
1:35 ## Afternoon
11:35 ## Afternoon
示例代码:
m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "%H:%M")
print m2
预期输出:
13:35
实际输出:
1900-01-01 01:35:00
我尝试了第二个变体,但再次没有帮助:/
m2 = "1:35" ## This is in the afternoon.
m2split = m2.split(":")
if len(m2split[0]) == 1:
m2 = ("""%s%s%s%s""" % ("0", m2split[0], ":", m2split[1]))
print m2
m2temp = datetime.strptime(m2, "%I:%M")
m2 = m2temp.strftime("%H:%M")
我做错了什么,我该如何解决?
【问题讨论】:
-
字符串
"1:35"中没有任何内容表明现在是下午时间,因此strptime()将假定现在是上午。要表示下午,您需要某种上午/下午指示器。 -
SO 13855111主要是逆问题,将24小时制转换为12小时制。
-
@JonathanLeffler 问题是我不能自动将 PM 添加到字符串时间?如果 m2 值是 10:00 到 12:00,而实际时间是 10:00 到 13:00(早上到下午 1 点),那么 m2 应该被认为是早上时间,其他一切都应该被认为是下午时间。跨度>
-
如果你有决定时间是上午还是下午的规则,你需要将它们写在代码中。 Python 无法读懂你的想法。
标签: python python-2.7 time