datetime.datetime.utcnow()
为什么这个datetime没有任何时区信息,因为它是一个明确的UTC日期时间?
我希望它包含tzinfo。
datetime.datetime.utcnow()
为什么这个datetime没有任何时区信息,因为它是一个明确的UTC日期时间?
我希望它包含tzinfo。
当前回答
标准的Python库直到Python 3.2才包含任何tzinfo类。我只能猜测原因。我个人认为没有为UTC包含tzinfo类是一个错误,因为它没有足够的争议性,可以有一个标准的实现。尽管库中没有实现,但tzinfo文档中给出了一个示例。
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
有了UTC tzinfo对象后,仍然不能将其用于utcnow。获取当前时间作为感知datetime对象:
from datetime import datetime
now = datetime.now(utc)
在Python 3.2中,他们终于在库中加入了一个UTC tzinfo类:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
在Python 3.9中,他们为所有其他时区创建了tzinfo类。有关详细信息,请参阅标准库中的PEP 615—对IANA时区数据库的支持。
其他回答
它还应该包括and now()。相关的问题。
因此,在此之前,now()优先于today()和utcnow()。
from datetime import datetime, timezone
utc = timezone.utc
date = datetime.now(utc)
print(date) # 2022-04-06 05:40:13.025347+00:00
UTC日期不需要任何时区信息,因为它们是UTC,这根据定义意味着它们没有偏移量。
标准的Python库直到Python 3.2才包含任何tzinfo类。我只能猜测原因。我个人认为没有为UTC包含tzinfo类是一个错误,因为它没有足够的争议性,可以有一个标准的实现。尽管库中没有实现,但tzinfo文档中给出了一个示例。
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
有了UTC tzinfo对象后,仍然不能将其用于utcnow。获取当前时间作为感知datetime对象:
from datetime import datetime
now = datetime.now(utc)
在Python 3.2中,他们终于在库中加入了一个UTC tzinfo类:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
在Python 3.9中,他们为所有其他时区创建了tzinfo类。有关详细信息,请参阅标准库中的PEP 615—对IANA时区数据库的支持。
在Python 3.2+中添加时区信息
import datetime
>>> d = datetime.datetime.now(tz=datetime.timezone.utc)
>>> print(d.tzinfo)
'UTC+00:00'
The behaviour of datetime.datetime.utcnow() returning UTC time as naive datetime object is obviously problematic and must be fixed. It can lead to unexpected result if your system local timezone is not UTC, since datetime library presume naive datetime object to represent system local time. For example, datetime.datetime.utcnow().timestaamp() gives timestamp of 4 hours ahead from correct value on my computer. Also, as of python 3.6, datetime.astimezone() can be called on naive datetime instances, but datetime.datetime.utcnow().astimezone(any_timezone) gives wrong result unless your system local timezone is UTC.