python - 如何在 Python 中构造 UTC `datetime` 对象?

标签 python datetime timezone

我正在使用 the datetime.datetime class来自 Python 标准库。我希望用 UTC 时区构造这个类的一个实例。为此,我收集到我需要将 the tzinfo class 的一些实例作为 tzinfo 参数传递给 datetime 构造函数。 .

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)

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

最佳答案

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

关于python - 如何在 Python 中构造 UTC `datetime` 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28498163/

相关文章:

python - 为什么我的 apply 函数不返回字符串的长度?

python - 我是否需要降级我的 conda 版本才能安装模块?

java - 从 JAVA 日期中删除秒和时区信息

java - UTC 时区未检测夏令时

java - java.util.Date 中的默认时区是什么

python - python如何知道从命令行运行?

python - 在python中杀死sudo启动的子进程

jquery - 将字符串转换为时间对象

vba - 如何在每半小时后获得最近的日期

python - 如何在 Python 中获取 "timezone aware"的 datetime.today() 值?