簡體   English   中英

Datetime 夏令時轉換問題 [Python]

[英]Datetime Daylight savings transition problem [Python]

由於上周六/周日過渡到夏令時,在從 UTC 轉換為 CET 時,我的時間戳字段出現以下錯誤:

AmbiguousTimeError: Cannot infer dst time from 2020-07-31 11:17:18+00:00, try using the 'ambiguous' argument

#將時間戳字段轉換為 CET(歐洲,柏林)

df['timestamp_berlin_time'] = df['timestamp'].dt.tz_localize('Europe/Berlin')

我嘗試了以下代碼段:

df['timestamp_berlin_time'] = df['timestamp'].dt.tz_localize('CET',ambiguous='infer')

但這給了我這個錯誤:

AmbiguousTimeError: 2020-07-31 11:17:18+00:00

數據樣本:

0  2020-07-31 11:17:18+00:00
1  2020-07-31 11:17:18+00:00
2  2020-08-31 16:26:42+00:00
3  2020-10-20 07:28:46+00:00
4  2020-10-01 22:11:33+00:00

名稱:時間戳,數據類型:datetime64[ns, UTC]

如果您的輸入是 UTC 但尚未設置 UTC,您可以先本地化為 UTC,例如:

df['timestamp'] = df['timestamp'].dt.tz_localize('UTC')

如果您的輸入已經轉換為 UTC,您可以簡單地tz_convert ,例如:

s = pd.Series(pd.to_datetime(['2020-10-25 00:40:03.925000', 
                              '2020-10-25 01:40:03.925000', 
                              '2020-10-25 02:40:03.925000'], utc=True))

s.dt.tz_convert('Europe/Berlin')
# 0   2020-10-25 02:40:03.925000+02:00
# 1   2020-10-25 02:40:03.925000+01:00
# 2   2020-10-25 03:40:03.925000+01:00
# dtype: datetime64[ns, Europe/Berlin]

如果您的輸入時間戳代表本地時間(此處:歐洲/柏林時區),您可以嘗試根據順序推斷 DST 轉換:

s = pd.Series(pd.to_datetime(['2020-10-25 02:40:03.925000', 
                              '2020-10-25 02:40:03.925000', 
                              '2020-10-25 03:40:03.925000']))

s.dt.tz_localize('Europe/Berlin', ambiguous='infer')
# 0   2020-10-25 02:40:03.925000+02:00
# 1   2020-10-25 02:40:03.925000+01:00
# 2   2020-10-25 03:40:03.925000+01:00
# dtype: datetime64[ns, Europe/Berlin]

注意:CET 不是地理意義上的時區。 由於歷史原因,pytz 可以處理其中的一些,但不要指望它。 在任何情況下,它都可能為您提供靜態 tz 偏移量 - 如果您希望它包含 DST 轉換,這不是您想要的。

暫無
暫無

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

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