将 12 小时格式时间字符串(带 am/pm)转换为 24 小时格式的 UTC

Converting 12 hour format time string (with am/pm) into UTC in 24 hour format

我有时间字符串 11:15am11:15pm。 我正在尝试将此字符串转换为 24 小时格式的 UTC 时区。

从 EST 到 UTC

例如:当我通过 11:15am 它应该转换为 15:15 当我通过 11:15pm 然后它应该转换为 3:15.

我有我正在尝试的代码:

def appointment_time_string(time_str):
    import datetime
    a = time_str.split()[0]

    # b =  re.findall(r"[^\W\d_]+|\d+",a)

    # c = str(int(b[0]) + 4) + ":" + b[1]
    # print("c", c)



    in_time = datetime.datetime.strptime(a,'%I:%M%p')

    print("In Time", in_time)

    start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))

    print("Start TIme", start_time)

    if time_str.split()[3] == 'Today,':
        start_date = datetime.datetime.utcnow().strftime("%Y-%m-%dT")
    elif time_str.split()[3] == 'Tomorrow,':
        today = datetime.date.today( )
        start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%dT")

    appointment_time = str(start_date) + str(start_time)

    return appointment_time

x = appointment_time_string(time_str)
print("x", x)

但这只是转换为 24 小时而不是 UTC。

要将时间从 12 小时格式转换为 24 小时格式,您可以使用以下代码:

from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'

为了将时间从EST转换为UTC,最可靠的方法是使用第三方库pytz. Refer How to convert EST/EDT to GMT?了解更多详情

使用提供的 options/solutions 开发了以下脚本以满足我的要求。

def appointment_time_string(time_str):

    import datetime
    import pytz

    a = time_str.split()[0]

    in_time = datetime.datetime.strptime(a,'%I:%M%p')

    start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S"))

    if time_str.split()[3] == 'Today,':
        start_date = datetime.datetime.utcnow().strftime("%Y-%m-%d")
    elif time_str.split()[3] == 'Tomorrow,':
        today = datetime.date.today( )
        start_date = (today + datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    appointment_time = str(start_date) + " " + str(start_time)

    # print("Provided Time", appointment_time)

    utc=pytz.utc
    eastern=pytz.timezone('US/Eastern')
    fmt='%Y-%m-%dT%H:%M:%SZ'
    # testeddate = '2016-09-14 22:30:00'

    test_date = appointment_time

    dt_obj = datetime.datetime.strptime(test_date,'%Y-%m-%d %H:%M:%S')
    dt_str = datetime.datetime.strftime(dt_obj, '%m/%d/%Y %H:%M:%S')
    date=datetime.datetime.strptime(dt_str,"%m/%d/%Y %H:%M:%S")
    date_eastern=eastern.localize(date,is_dst=None)
    date_utc=date_eastern.astimezone(utc)

    # print("Required Time", date_utc.strftime(fmt))

    return date_utc.strftime(fmt)