【发布时间】:2021-01-31 11:19:54
【问题描述】:
我尝试了以下方法来更改时区 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]? - 为什么
tz_convert说当dtypes显示UTC 时时间戳太天真了?
编辑:
this question 的答案实际上通过使用 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]
【问题讨论】:
-
你有一些样本数据吗?
-
你说得对,需要样本数据和可复现的例子,我准备一个可复现的例子。
标签: python pandas numpy datetime64