如何在Python中将AM/PM时间戳转换为24小时格式?

31

我正在尝试将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")
我做错了什么,该怎么修正?

https://dev59.com/rGYr5IYBdhLWcg3wOXsQ - The Humble Rat
9
字符串 "1:35" 中没有任何内容表明它是下午时间,因此 strptime() 会假定它是上午时间。要表示下午时间,需要使用一些形式的上午/下午指示器。 - Jonathan Leffler
SO 13855111主要涉及转换问题,即将24小时制时间转换为12小时制时间。 - Jonathan Leffler
@JonathanLeffler 问题是我无法自动将 PM 添加到时间字符串中?如果 m2 值为 10:00 到 12:00,而实际时间为上午 10:00 到下午 1:00(上午到下午 1 点),则应将 m2 视为上午时间,其他所有时间均应视为下午时间。 - Ryflex
1
如果您有决定时间是上午还是下午的规则,您需要将它们编写成代码。Python 无法读取您的思想。 - dan04
@dan04 我刚刚制定了这些规则来解决这个问题... - Ryflex
16个回答

47
该方法使用strptime和strftime函数,使用格式指令,参照https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior。%H表示24小时制,%I表示12小时制。当使用12小时制时,%p表示上午还是下午。
    >>> 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

33

你需要明确指出你的意思是下午而不是上午。

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

2
此外,他需要使用 strftime 函数来获得所需的输出。 - Robᵩ
@dan04 我的字符串(m2)是在其他地方自动生成的,我无法在它们上面添加“PM”。我已经编辑了我的原始帖子以展示一些时间。 - Ryflex
这确实应该是答案。其他答案都是克隆,而有些答案则会通过使用额外的计算和资源来实现结果,与本提案相比是不必要的。 - ivanleoncz

7

希望你能尝试这个 :)

代码:

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

输出:

13:35

3
我知道这是一个旧答案,但为什么你的格式字符串要用三个引号括起来?另外,m2已经是一个字符串了,你可以直接写成 m2 += " AM"。同时,在 m2 >= "10:00" 中进行了字符串比较。为什么这个答案被接受... - Enrico Borba

5

如果日期是以这种格式表示的(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)

优雅的算法不使用太多内置函数。 - Fahad
elegant! beautiful! - zx1986

4
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)

2

试试这个

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

2
def timeConversion(s):
    if "PM" in s:
        s=s.replace("PM"," ")
        t= s.split(":")
        if t[0] != '12':
            t[0]=str(int(t[0])+12)
            s= (":").join(t)
        return s
    else:
        s = s.replace("AM"," ")
        t= s.split(":")
        if t[0] == '12':
            t[0]='00'
            s= (":").join(t)
        return s

2
这实际上是最简单的方法。不错! - Raghav Gupta

1

还有一种干净的方法来做到这一点

def format_to_24hr(twelve_hour_time): return datetime.strftime( datetime.strptime( twelve_hour_time, '%Y-%m-%d %I:%M:%S %p' ), "%Y-%m-%d %H:%M:%S")


0

在表示小时的地方,不要使用“H”,而应该像下面的例子一样使用“I”:

from datetime import *
m2 = 'Dec 14 2018 1:07PM'
m2 = datetime.strptime(m2, '%b %d %Y %I:%M%p')
print(m2)

请检查此链接

0
这是我的解决方案,使用Python内置函数将12小时时间格式转换为24小时时间格式
def time_conversion(s):
    if s.endswith('AM') and s.startswith('12'):
        s = s.replace('12', '00')
    if s.endswith('PM') and not s.startswith('12'):
        time_s = s.split(':')
        time_s[0] = str(int(time_s[0]) + 12)
        s = ":".join(time_s)
        
    s = s.replace('AM', '').replace('PM', '')
    
    return s
          

time_conversion('07:05:45PM') 

19:05:45

我建议将代码改为:time_s[0] = '%02d' % (int(time_s[0]) + 12) - 00__00__00

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