我正在使用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就可以了。我该怎么做呢?