将熊猫列 datetime64 的时区从 UTC 转换为 America/New_York

时间:2021-01-31 11:19:54

标签: python pandas numpy datetime64

我尝试了以下更改时区 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. tz_convert 显示 UTC 时,为什么 dtypes 说时间戳是 tz-naive?

编辑: 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]

1 个答案:

答案 0 :(得分:1)

这种情况只有在您的数据帧具有 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_localize 不返回 datetime64[ns,America/New_York]

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

此行为在 documentation of tz_localize 中有明确描述:

<块引用>

此操作本地化索引。将值本地化 timezone-naive 系列,使用 Series.dt.tz_localize()

2.当 tz_convert 显示 UTC 时,为什么 dtypes 说时间戳是 tz-naive?

与 1 相同的原因。 - 它尝试转换没有时区的索引。 documentation 在这里不如 tz_localize 清楚。