如何将时间从 UTC 转换为 EST?

How to convert time from UTC to EST?

我有这样一个数据框:

          dt                  |  value
2019-01-01 00:00:00 +0000 UTC |  49.0
2019-01-01 01:00:00 +0000 UTC |  39.8
2019-01-01 02:00:00 +0000 UTC |  23.4
2019-01-01 03:00:00 +0000 UTC |  45.3

此时间戳采用 UTC 时区,但我想将其转换为 EST。这是我的尝试:

dtobj = pd.to_datetime(data['dt'], format='%Y-%m-%d %H:%M:%S +0000 %Z')
dtobj = dtobj.replace(tzinfo=ZoneInfo('US/Eastern'))

但出现以下错误:

TypeError: replace() got an unexpected keyword argument 'tzinfo'

我没有找到一个明确的答案来解释为什么会发生这个错误。还有其他转换时区的方法吗?

您需要使用 pytz 模块(可从 PyPI 获得):

import pytz
from datetime import datetime

est = pytz.timezone('US/Eastern')
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S %Z%z'

dateTimeUtc= datetime(2016, 1, 24, 18, 0, 0, tzinfo=utc)
dateTimeUtc.astimezone(est).strftime(fmt)

尝试使用 dt.tz_convert:

>>> df['dt'] = pd.to_datetime(df['dt'], format='%Y-%m-%d %H:%M:%S +0000 %Z')
>>> df['dt'] = df['dt'].dt.tz_convert('US/Eastern')
>>> df
                         dt  value
0 2018-12-31 19:00:00-05:00   49.0
1 2018-12-31 20:00:00-05:00   39.8
2 2018-12-31 21:00:00-05:00   23.4
3 2018-12-31 22:00:00-05:00   45.3
>>>