datetime.datetime.utcnow()
为什么这个datetime没有任何时区信息,因为它是一个明确的UTC日期时间?
我希望它包含tzinfo。
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
其他回答
在Python 3.2+中添加时区信息
import datetime
>>> d = datetime.datetime.now(tz=datetime.timezone.utc)
>>> print(d.tzinfo)
'UTC+00:00'
它还应该包括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
from datetime import datetime
from dateutil.relativedelta import relativedelta
d = datetime.now()
date = datetime.isoformat(d).split('.')[0]
d_month = datetime.today() + relativedelta(months=1)
next_month = datetime.isoformat(d_month).split('.')[0]
注意,对于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)
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.