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

问题描述 投票:0回答:17

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

我做错了什么以及如何解决这个问题?

python time datetime-conversion
17个回答
47
投票

此方法使用 strptime 和 strftime 以及格式指令,如 https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior,%H 是 24 小时时钟,%I 是12 小时制,当使用 12 小时制时,如果是 AM 或 PM,%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

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

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)

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)

3
投票
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
投票

试试这个😊

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

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
投票

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

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

定义时间转换:

    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

0
投票

最基本的方法是:

t_from_str_12h = datetime.datetime.strptime(s, "%I:%M:%S%p")
str_24h =  t_from_str.strftime("%H:%M:%S")

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]

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

0
投票
# 12-hour to 24-hour time format
import re

s = '12:05:45PM'


def timeConversion(s):
    hour = s.split(':')
    lastString = re.split('(\d+)', hour[2])
    if len(hour[2]) > 2:
        hour[2] = lastString[1]
    if 'AM' not in hour or 'am' not in hour or int(hour[0]) < 12:
        if (lastString.__contains__('PM') and int(hour[0]) < 12) or (lastString.__contains__('pm') and int(hour[0]) < 12):
            hour[0] = str(int(hour[0]) + 12)
    if hour[0] == '12' and (lastString.__contains__('AM') or lastString.count('am')):
        hour[0] = '00'
    x = "{d}:{m}:{y}".format(d=hour[0], m=hour[1], y=hour[2])
    return x


print(timeConversion(s))

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

0
投票

我们可以将12和24视为数字系统

碱基分别为 12 和 24。 在这种情况下,AM/PM 充当以 12 为底的数字系统中第二位的值 0 或 1。

例如:

时间 基数 12 基数24
凌晨3点 03 03
下午3点 13 0天
晚上11点 1b 0n

要从 12 进制转换为 24 进制,以下函数会有所帮助。

def timeConversion(s):
    second_order = {
        "PM": 1,
        "AM": 0
    }
    hours, rest_time, ampm = s[:2], s[2:-2], s[-2:]
    result_hour = second_order[ampm] * 12 + int(hours) % 12
    return f'{result_hour:02d}{rest_time}'

-1
投票

%H
小时(24 小时制),以零填充的十进制数。
%I
小时(12 小时制),以零填充的十进制数。

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "<b>%I</b>:%M")
print(m2)
© www.soinside.com 2019 - 2024. All rights reserved.