linux 机器出现时区错误

Getting astimezone error in linux machine

我正在使用 linux aws 机器,当我使用 datetime.datetime.now 时存在时区差异。所以我尝试了这种方法来克服时区错误

format = "%Y-%m-%d %H:%M:%S %Z%z"
current_date = datetime.datetime.now()
now_asia = current_date.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))

当我使用 window 机器时,我没有遇到任何错误。当我在我的 linux 机器上使用相同的行时,我得到 "ValueError: astimezone() cannot be applied to a naive datetime"

为了调试这个,我尝试了这个 link 中提到的方法 pytz and astimezone() cannot be applied to a naive datetime

当我尝试第一个答案时,我没有收到任何错误,但时区没有转换。 当我尝试第二个答案时,出现错误“AttributeError: 'module' object has no attribute 'utcnow'

我试过了

>>>loc_date = local_tz.localize(current_date)
>>> loc_date
datetime.datetime(2020, 4, 6, 7, 23, 36, 702645, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)
>>> loc_date.strftime(format)
'2020-04-06 07:23:36 IST+05:30'

我明白了,所以根据印度时间,如果我们添加 5:30,它将是正确的。我应该怎么做。

请确认您确实是 运行 云中的 Python 3.7 解释器。引用 the documentation for the astimezone() function:

Changed in version 3.6: The astimezone() method can now be called on naive instances that are presumed to represent system local time.

事实上,我刚刚使用 Python 3.5.9 和 pytz 2019.3 测试了脚本,我得到

  File "timez.py", line 6, in <module>
    now_asia = current_date.astimezone(timezone('Asia/Kolkata'))
ValueError: astimezone() cannot be applied to a naive datetime

但是在 Amazon Linux 2 AMI 实例上使用 Python 3.7.6 时,代码运行正确。

尽管如此,我建议从一开始就使用时区感知日期时间。

the code you're referencing 中,您发现没有 utcnow 属性,因为该代码导入了 from datetime import datetime,而您正在执行 import datetime。要使其工作,您可以使用

now_utc = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

但请注意,Python documentation 现在建议您使用 datetime.now 中的 tz 参数:

import datetime
import pytz

now_utc = datetime.datetime.now(tz=pytz.utc)
local_tz = pytz.timezone('Asia/Kolkata')
now_asia = now_utc.astimezone(local_tz)

format = "%Y-%m-%d %H:%M:%S %Z%z"
print(now_asia.strftime(format))

在我的例子中打印 2020-04-22 09:25:21 IST+0530