Python 将pandas列datetime64的时区从UTC转换为美国/纽约
我尝试了以下更改时区数据帧的方法:Python 将pandas列datetime64的时区从UTC转换为美国/纽约,python,pandas,numpy,datetime64,Python,Pandas,Numpy,Datetime64,我尝试了以下更改时区数据帧的方法: 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 (mos
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\u localize
不返回datetime64[ns,美国/纽约]
dtypes
显示UTC时,为什么tz\u convert
说时间戳是tz-naive编辑: 的答案实际上通过使用
tz\u 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]
只有当您的数据帧有一个tz naive datetime索引时,这种情况才可能发生
import pandas as pd
df = pd.DataFrame({'column_datetime': pd.to_datetime('2005-01-03 14:30', utc=True)},
index=[pd.to_datetime('2005-01-03 14:30')])
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)
回答你的问题:
1。为什么tz\u localize
不返回datetime64[ns,美国/纽约]
?
tz_localize
本地化索引,而不是序列值(对于后者,您需要dt
访问器,正如您已经发现的那样)。您可以通过打印df['column\u datetime'].tz\u localize('America/New\u York').index.dtype来验证这一点,它是datetime64[ns,America/New\u York]
。您打印了在此操作中未更改的值类型
该行为在以下文件中有明确描述:
此操作将索引本地化。将值本地化为
时区原始序列,使用Series.dt.tz_localize()
2。当dtypes
显示UTC时,为什么tz\u convert
说时间戳是tz幼稚的?
与1相同的原因它尝试转换没有时区的索引。这里的问题不是很清楚,关于tz_localize
你有一些样本数据吗?你是对的,样本数据和可复制的示例是必需的,我将准备一个可以复制的示例。