关于python:将12小时转换为24小时

Convert 12 hour into 24 hour times

我想把12小时转换成24小时…

自动示例时间:

1
2
3
4
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

示例代码:

1
2
3
m2 ="1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2,"%H:%M")
print m2

号预期输出:

1
13:35

实际输出:

1
1900-01-01 01:35:00

我尝试了第二种变体,但再次没有帮助:/

1
2
3
4
5
6
7
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")

我做错了什么?我该怎么解决?


您需要指定您的意思是PM而不是AM。

1
2
3
4
5
>>> from datetime import *
>>> m2 = '1:35 PM'
>>> m2 = datetime.strptime(m2, '%I:%M %p')
>>> print(m2)
1900-01-01 13:35:00


根据https://docs.python.org/2/library/datetime.html strftime strptime behavior,此方法使用strptime和strftime,其中,%h是24小时制时钟,%i是12小时制时钟,当使用12小时制时钟时,如果是AM或PM,则%p是合格的。

1
2
3
4
5
6
    >>> 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


试试这个:)

代码:

1
2
3
4
5
6
7
8
9
10
11
12
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

号输出:

1
13:35


1
2
3
4
5
6
7
8
time = raw_input().strip() # input format in hh:mm:ssAM/PM
t_splt = time.split(':')
if t_splt[2][2:] == 'PM' and t_splt[0] != '12':
    t_splt[0] = str(12+ int(t_splt[0]))
elif int(t_splt[0])==12 and t_splt[2][2:] == 'AM':
    t_splt[0] = '00'
t_splt[2] = t_splt[2][:2]
print ':'.join(t_splt)

如果日期采用此格式(hh:mm:sspm/am),则以下代码有效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)


还有一种干净的方法

埃多克斯1〔2〕


Try this ??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
dicti =
{'01':13,'02':14,'03':15,'04':16,'05':17,'06':18,'07':19,'08':20,'09':21,'10':22,'11':23,'12':12}
s = '12:40:22PM'
if s.endswith('AM'):
if s.startswith('12'):
    s1=s[:8]
    bb=s1.replace('12','00')
    print bb
else:
    s1=s[:8]
    print s1
else:
s1=s[:8]
time= str(s[:2])
ora=str(dicti[time])
aa=s1.replace(time,ora)
print aa


%H小时(24小时制)作为零填充十进制数。%I小时(12小时制)为零填充十进制数。

1
2
3
m2 ="1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2,"%I:%M")
print(m2)