如何将python datetime对象转换为UTC datetime?

时间:2019-11-21 06:29:19

标签: python datetime python-datetime pytz django-timezone

以下代码段是我正在尝试将datetime字符串和给定时区转换为UTC datetime对象的代码。但是,输出只是一个与给定字符串具有相同时间的datetime对象。我究竟做错了什么?我似乎完全按照这篇文章中的概述进行操作:How to convert local time string to UTC?

from django.utils.dateparse import parse_datetime

import pytz

def localized_to_utc(datetime_str, dest_tz):
    """
    Utility function that parses a datetime string,
    localizing it to the provided time zone before
    converting it to UTC.

    :param datetime_str: String that can be parsed
    :param dest_tz: Destination time zone
    :return: datetime object
    """
    tz = pytz.timezone(dest_tz)
    dt = parse_datetime(datetime_str)

    # Localize to provided time zone
    tz.localize(dt)

    # Convert to UTC and return
    return dt.astimezone(pytz.utc)

tm = localized_to_utc("2019-11-20 16:45:00", "US/Central")

print(tm)//output: 2019-11-20 16:45:00+00:00

0 个答案:

没有答案