转换UTC到CST

时间:2019-12-02 13:24:37

标签: python-3.x python-datetime

我编写了以下函数以将UTC转换为CST(正常工作):

import datetime

def utc_datetime_to_cst_1(dt_now):
    """
    To convert UTC into CST, subtract 6 hours
    During daylight saving (summer) time, you would only subtract 5 hours

    :param dt_now: current date time - UTC format
    :return: CST datetime
    """
    # UTC is 6 hours ahead CST
    dt_now = dt_now - datetime.timedelta(hours=6)

    # If DST, increment one hour
    # IGNORE THIS PART FOR NOW
    #dt_now = dt_now + datetime.timedelta(hours=1)

    # Return CST datetime
    return dt_now

我试图创建一种更好的方法,所以我附带了以下功能:

import datetime
from pytz import utc, timezone

def utc_datetime_to_cst_2(date_time):
    """
    Converts UTC date time to CST

    :param date_time: date time
    :return: date time in CST
    """
    # Load current date as UTC
    utc_now = utc.localize(date_time)
    eastern = timezone('US/Eastern')

    # Return as CST
    return utc_now.astimezone(eastern)

同时调用这两者时:

current_datetime = datetime.datetime(year=2019, month=12, day=2, hour=23)
print(current_datetime)
print(utc_datetime_to_cst_1(current_datetime))
print(utc_datetime_to_cst_2(current_datetime))

我得到以下信息:

2019-12-02 23:00:00
2019-12-02 17:00:00
2019-12-02 18:00:00-05:00

因此utc_datetime_to_cst_2并未转换我期望的方式,因为我应该拥有now()-6h。有什么想法吗?

谢谢!

0 个答案:

没有答案