如何在 Python 中构建 UTC `datetime` 对象?

How do I construct a UTC `datetime` object in Python?

我正在使用 the datetime.datetime class from the Python standard library. I wish to construct an instance of this class with the UTC timezone. To do so, I gather that I need to pass as the tzinfo argument to the datetime constructor some instance of the tzinfo class

The documentation for the tzinfo class 表示:

tzinfo is an abstract base class, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module does not supply any concrete subclasses of tzinfo.

现在我被难住了。我只想代表"UTC"。我应该能够使用大约三个字符来做到这一点,就像这样

import timezones
...
t = datetime(2015, 2, 1, 15, 16, 17, 345, timezones.UTC)

简而言之,我不会按照文档告诉我的去做。那么我的选择是什么?

我在pytz中用了很多,对这个模块非常满意。

pytz

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).

另外我会推荐阅读:Understanding DateTime, tzinfo, timedelta & TimeZone Conversions in python

自 Python 3.2:

以来,stdlib 中有固定偏移时区
from datetime import datetime, timezone

t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=timezone.utc)

构造函数是:

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

文档 link.

尽管在早期版本上很容易实现 utc 时区:

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTCtzinfo(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTCtzinfo()
t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=utc)