20

我正在尝试将时间从 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")

我做错了什么,我该如何解决?

4

14 回答 14

36

这种方法使用带有格式指令的 strptime 和 strftime,按照https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior, %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
于 2016-02-21T19:51:51.407 回答
27

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

>>> from datetime import *
>>> m2 = '1:35 PM'
>>> m2 = datetime.strptime(m2, '%I:%M %p')
>>> print(m2)
1900-01-01 13:35:00
于 2013-10-07T15:57:08.103 回答
5

试试这个 :)

代码:

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
于 2013-10-07T17:59:35.747 回答
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)
于 2016-04-28T17:56:30.317 回答
3

如果日期采用这种格式 (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)
于 2017-11-27T07:16:49.473 回答
1

试试这个

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
于 2017-07-28T17:35:47.467 回答
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")

于 2018-12-13T10:20:59.917 回答
1
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
于 2020-07-08T13:29:51.437 回答
0

不要使用“H”作为小时指示,而是使用“I”,如下面的示例中所述:

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

请检查此链接

于 2020-04-14T07:21:53.547 回答
0

将 12 小时时间格式转换为 24 小时时间格式

''' 检查时间是 'AM' 还是 'PM' 以及是否从 12 开始(中午或早上)。如果时间在中午 12 点之后,那么我们将其添加
12,否则我们让它保持原样。如果时间是早上 12 点,我们将 12 转换为 (00) '''

def timeConversion(s):

    if s[-2:] == 'PM' and s[:2] != '12':
        time = s.strip('PM')
        conv_time = str(int(time[:2])+12)+time[2:]

    elif s[-2:] == 'PM' and s[:2] == '12':
        conv_time = s.strip('PM')

    elif s[-2:] == 'AM' and s[:2] == '12':
        time = s.strip('AM')
        conv_time = '0'+str(int(time[:2])-12)+time[2:]

    else:
        conv_time = s.strip('AM')
        
    return conv_time
于 2020-11-16T14:07:28.183 回答
0

最基本的方法是:

t_from_str_12h = datetime.datetime.strptime(s, "%I:%M:%S%p")
str_24h =  t_from_str.strftime("%H:%M:%S")
于 2020-12-17T13:31:39.720 回答
0
#format HH:MM PM
def convert_to_24_h(hour):
    if "AM" in hour:
        if "12" in hour[:2]:
            return "00" + hour[2:-2]
        return hour[:-2]
    elif "PM" in hour:
        if "12" in hour[:2]:
            return hour[:-2]
    return str(int(hour[:2]) + 12) + hour[2:5]
于 2021-01-08T15:25:22.220 回答
0

由于大多数手动计算似乎有点复杂,我分享我的做法。

# Assumption: Time format (hh:mm am/pm) - You can add seconds as well if you need
def to_24hr(time_in_12hr):
    hr_min, am_pm = time_in_12hr.lower().split()
    hrs, mins = [int(i) for i in hr_min.split(":")]
    hrs %= 12
    hrs += 12 if am_pm == 'pm' else 0
    return f"{hrs}:{mins}"

print(to_24hr('12:00 AM'))
于 2021-12-23T05:56:08.623 回答
-1

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

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "<b>%I</b>:%M")
print(m2)
于 2018-04-06T17:18:51.567 回答