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

时间:2016-09-14 15:48:25

标签: python python-2.x

我有时间字符串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。

2 个答案:

答案 0 :(得分:2)

要将时间从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。有关详细信息,请参阅How to convert EST/EDT to GMT?

答案 1 :(得分:0)

使用提供的选项/解决方案开发以下脚本以满足我的要求。

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)