如何在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个回答

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

最基本的方法是:

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]

请使用每个缩进级别4个空格。参见 PEP 8 -- Python代码风格指南 - AcK

0

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

''' 检查时间是否为“上午”或“下午”,以及是否以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

1
如果您能提供一些关于您的解决方案的最基本的说明,那将会非常有帮助。 - Serge de Gosson de Varennes

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

-1

%H表示小时数(24小时制),用零填充的十进制数字。
%I表示小时数(12小时制),用零填充的十进制数字。

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "<b>%I</b>:%M")
print(m2)

%H 表示小时(24小时制),以零填充的十进制数。<br> %I 表示小时(12小时制),以零填充的十进制数。m2 = "1:35" ## 这是下午时间。m2 = datetime.strptime(m2, "%I:%M") print(m2) - szerem
虽然这段代码片段可能解决了问题,但包括解释有助于提高您的回答质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您提出代码建议的原因。 - Stefan Crain

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