簡體   English   中英

在 linux 機器中出現 astimezone 錯誤

[英]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”

為了調試這個我嘗試了這個鏈接中提到的方法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 解釋器。 引用astimezone() function 的文檔

在 3.6 版更改:現在可以在假定代表系統本地時間的幼稚實例上調用astimezone() 方法。

事實上,我剛剛使用 Python 3.5.9 和pytz測試了腳本,我得到了

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM