我尝试了以下方法来更改时区 Pandas 数据框:
print(df['column_datetime'].dtypes)
print(df['column_datetime'].tz_localize('America/New_York').dtypes)
print(df['column_datetime'].tz_convert('America/New_York').dtypes)
这给了我:
datetime64[ns, UTC]
datetime64[ns, UTC]
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.6/site-packages/pandas/core/generic.py", line 9484, in tz_convert
ax = _tz_convert(ax, tz)
File "/home/ubuntu/.local/lib/python3.6/site-packages/pandas/core/generic.py", line 9472, in _tz_convert
ax = ax.tz_convert(tz)
File "/home/ubuntu/.local/lib/python3.6/site-packages/pandas/core/indexes/extension.py", line 78, in method
result = attr(self._data, *args, **kwargs)
File "/home/ubuntu/.local/lib/python3.6/site-packages/pandas/core/arrays/datetimes.py", line 803, in tz_convert
"Cannot convert tz-naive timestamps, use tz_localize to localize"
TypeError: Cannot convert tz-naive timestamps, use tz_localize to localize
两个问题:
- 为什么
tz_localize
不返回datetime64[ns,America/New_York]
? - 为什么在显示 UTC
tz_convert
时说时间戳是 tz-naive ?dtypes
编辑:这个问题的答案实际上通过使用解决了这个问题tz_convert
。
import numpy as np
import pandas as pd
x = pd.Series(np.datetime64('2005-01-03 14:30:00.000000000'))
y = x.dt.tz_localize('UTC')
z = y.dt.tz_convert('America/New_York')
z
---
0 2005-01-03 09:30:00-05:00
dtype: datetime64[ns, America/New_York]