datetime.datetime.utcnow()

为什么这个datetime没有任何时区信息,因为它是一个明确的UTC日期时间?

我希望它包含tzinfo。


当前回答

它还应该包括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 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.

Julien Danjou写了一篇很好的文章,解释了为什么你永远不应该处理时区问题。摘录:

实际上,Python datetime API总是返回未意识到的datetime对象, 这是非常不幸的。的确,只要你有了这个 对象,没有办法知道时区是什么,因此这些 对象本身非常“无用”。

遗憾的是,即使您可以使用utcnow(),您仍然不会看到您所发现的时区信息。

建议:

Always use aware datetime objects, i.e. with timezone information. That makes sure you can compare them directly (aware and unaware datetime objects are not comparable) and will return them correctly to users. Leverage pytz to have timezone objects. Use ISO 8601 as the input and output string format. Use datetime.datetime.isoformat() to return timestamps as string formatted using that format, which includes the timezone information. If you need to parse strings containing ISO 8601 formatted timestamps, you can rely on iso8601, which returns timestamps with correct timezone information. This makes timestamps directly comparable.

注意,对于Python 3.2起,datetime模块包含datetime.timezone。datetime.utcnow()的文档说:

可感知的当前UTC日期时间可以通过调用datetime.now(timezone.utc)来获得。

因此,datetime.utcnow()不会设置tzinfo来指示它是UTC,但datetime.now(datetime.timezone.utc)会返回UTC时间并设置tzinfo。

所以你可以这样做:

>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2014, 7, 10, 2, 43, 55, 230107, tzinfo=datetime.timezone.utc)