如何在Python中构造UTC“datetime”对象?

2024-04-16 19:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python标准库中的the ^{} class。我想用UTC时区构造这个类的一个实例。为此,我认为需要将tzinfo参数作为datetime构造函数传递the ^{} class的某个实例。

The documentation for the ^{} 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)

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


Tags: ofthe实例参数标准datetimenotclass
2条回答

自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)

我在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

相关问题 更多 >