可靠地将数据帧从 EST(夏令时)转换为日本标准时间(无夏令时)

Reliably converting dataframe from EST (daylight savings time) to Japan standard time (no daylight savings time)

我有一个我认为很简单的问题,但随着我阅读更多内容并浏览此论坛上的问题,它变得越来越混乱。如果之前有人问过这个问题,我深表歉意,但到目前为止,我找不到任何来源同时处理下面提到的两个步骤。

问题:我有一个这样的数据帧(没有提到时区或偏移量)

Date Time 
2020-01-02 22:00:00
2020-01-03 01:00:00 
2002-01-03 01:05:00  

等等。这些时间在美国东部时间。 EST 遵循夏令时

我需要将其转换为不遵循夏令时的日本标准时间

所以首先,我需要将时间 2020-01-02 22:00:00 转换为 EST 日期时间对象。我打算用 datetime.strptime 但是我不知道把时区放在哪里

接下来,我需要将 EST 日期时间对象转换为日本标准时间。但我不确定 python 是否会自动计算出美国东部时间的夏令时开始时间。过去美国国会发生了一些变化,Python 怎么会知道这些。同样,如果将来美国国会做出一些改变,例如他们删除了夏令时,我们是否可以通过更新时区的 python 例程来保留相同的代码。

感谢您的任何意见

假设您的数据帧值是时区天真 a.k.a 没有时区的日期时间,那么您需要将 EST 时区与 DST 附加 tz_localize('EST', ambiguous='infer'),然后使用 tz_convert('Asia/Tokyo') 更改为正确的时间日本.

如果没有有关数据针对哪个城市的具体信息,则无法确定 DST 是否生效。根据https://www.timeanddate.com/time/zone/usa/new-york,纽约在 2020-05-07 之前是美国东部时间,然后将在 EDT UTC-04:00 到 10 月 31 日。

有关夏令时的详细信息,请参阅https://pandas.pydata.org/docs/reference/api/pandas.DatetimeIndex.tz_localize.html#pandas-datetimeindex-tz-localize

In some cases, inferring the DST is impossible. In such cases, you can pass an ndarray to the ambiguous parameter to set the DST explicitly

...

s.dt.tz_localize('CET', ambiguous=np.array([True, True, False]))

我从字符串值开始

# just str, not a datetime index
>>> df.info()                                                                                                                                                            
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 1 columns):
Datetime    3 non-null object
dtypes: object(1)
memory usage: 152.0+ bytes

# convert to datetime
>>> tz_naive = pd.to_datetime(df['Datetime'])
>>> tz_naive
0   2020-01-02 22:00:00
1   2020-01-03 01:00:00
2   2002-01-03 01:05:00
Name: Datetime, dtype: datetime64[ns]

>>> tz_aware = tz_naive.dt.tz_localize('EST', ambiguous='infer')
>>> tz_aware                                                                                                                                                              
0   2020-01-02 22:00:00-05:00
1   2020-01-03 01:00:00-05:00
2   2002-01-03 01:05:00-05:00
Name: Datetime, dtype: datetime64[ns, EST]

>>> tz_aware.dt.tz_convert('Asia/Tokyo')
0   2020-01-03 12:00:00+09:00
1   2020-01-03 15:00:00+09:00
2   2002-01-03 15:05:00+09:00
Name: Datetime, dtype: datetime64[ns, Asia/Tokyo]