我正在使用 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 standardtzinfo
methods needed by thedatetime
methods you use. Thedatetime
module does not supply any concrete subclasses oftzinfo
.
现在我被难住了。我想做的就是代表“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/