Ryf*_*lex 10 python time python-2.7
我试图将时间从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
Run Code Online (Sandbox Code Playgroud)
m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "%H:%M")
print m2
Run Code Online (Sandbox Code Playgroud)
13:35
Run Code Online (Sandbox Code Playgroud)
1900-01-01 01:35:00
Run Code Online (Sandbox Code Playgroud)
我尝试了第二种变化但又没有帮助:/
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")
Run Code Online (Sandbox Code Playgroud)
我做错了什么,我该如何解决这个问题?
dan*_*n04 21
您需要指定您的意思是PM而不是AM.
>>> from datetime import *
>>> m2 = '1:35 PM'
>>> m2 = datetime.strptime(m2, '%I:%M %p')
>>> print(m2)
1900-01-01 13:35:00
Run Code Online (Sandbox Code Playgroud)
mod*_*dpy 16
根据https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior,这种方法使用strptime和strftime格式指令,%H是24小时制,%I是12小时制当使用12小时时,%p符合AM或PM的条件.
>>> from datetime import datetime
>>> m2 = '1:35 PM'
>>> in_time = datetime.strptime(m2, "%I:%M %p")
>>> out_time = datetime.strftime(in_time, "%H:%M")
>>> print(out_time)
13:35
Run Code Online (Sandbox Code Playgroud)
试试这个 :)
currenttime = datetime.datetime.now().time().strftime("%H:%M")
if currenttime >= "10:00" and currenttime <= "13:00":
if m2 >= "10:00" and m2 >= "12:00":
m2 = ("""%s%s""" % (m2, " AM"))
else:
m2 = ("""%s%s""" % (m2, " PM"))
else:
m2 = ("""%s%s""" % (m2, " PM"))
m2 = datetime.datetime.strptime(m2, '%I:%M %p')
m2 = m2.strftime("%H:%M %p")
m2 = m2[:-3]
print m2
Run Code Online (Sandbox Code Playgroud)
13:35
Run Code Online (Sandbox Code Playgroud)
如果日期采用这种格式 (HH:MM:SSPM/AM),则以下代码有效:
a=''
def timeConversion(s):
if s[-2:] == "AM" :
if s[:2] == '12':
a = str('00' + s[2:8])
else:
a = s[:-2]
else:
if s[:2] == '12':
a = s[:-2]
else:
a = str(int(s[:2]) + 12) + s[2:8]
return a
s = '11:05:45AM'
result = timeConversion(s)
print(result)
Run Code Online (Sandbox Code Playgroud)