我正在使用 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”
为了调试这个,我尝试了这个链接中提到的方法 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
。
关于python - 在 linux 机器中获取 astimezone 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61054731/