1

我尝试了以下方法来更改时区 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

两个问题:

  1. 为什么tz_localize不返回datetime64[ns,America/New_York]
  2. 为什么在显示 UTCtz_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]
4

1 回答 1

1

仅当您的数据框具有 tz naive 日期时间索引时,这种情况才可能发生。

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_localize不退货datetime64[ns,America/New_York]

tz_localize本地化index,而不是系列的值(对于后者,您需要dt访问器,正如您已经发现的那样)。您可以通过打印df['column_datetime'].tz_localize('America/New_York').index.dtypewhich is来验证这一点datetime64[ns, America/New_York]。您打印了在此操作中未更改的值的类型。

这种行为在以下文档中tz_localize有明确描述:

此操作本地化索引。要本地化 timezone-naive Series 中的值,请使用Series.dt.tz_localize().

2. 为什么在显示 UTCtz_convert时说时间戳是 tz-naive ?dtypes

与 1 相同的原因。 - 它尝试转换没有时区的索引。这里的文档不像tz_localize.

于 2021-01-31T17:23:08.363 回答