在Linux机器上遇到astimezone错误

3

我正在使用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))

在我的Windows机器上运行时,没有出现任何错误。但是在我使用Linux机器时,相同的代码会出现"ValueError: 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版本? - norok2
我使用Python 3.7。 - user11862294
1个回答

2
请确认您确实在云中运行Python 3.7解释器。引用astimezone()函数的文档

从3.6版本开始:astimezone()方法现在可以在假定表示系统本地时间的原始实例上调用

事实上,我刚刚使用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时,代码可以正确运行。
尽管如此,我建议从一开始就使用带有时区信息的日期时间。
在你所引用的代码中,你得到了没有utcnow属性的信息,因为该代码导入了from datetime import datetime,而你正在使用import datetime。要使其工作,你需要使用:
now_utc = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

但请注意,Python文档现在建议您在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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接