【问题标题】:Convert timezone of a pandas column datetime64 from UTC to America/New_York将 pandas 列 datetime64 的时区从 UTC 转换为 America/New_York
【发布时间】: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

两个问题:

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


【解决方案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.dtype(即datetime64[ns, America/New_York])来验证这一点。您打印了在此操作中未更改的值的类型。

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

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

2。为什么tz_convert 说当dtypes 显示UTC 时时间戳太天真了?

与 1 相同的原因 - 它尝试转换没有时区的索引。 documentation 在这里并不像 tz_localize 那样清晰。

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 2017-04-29
    • 2020-11-05
    • 2019-11-27
    • 2015-01-26
    • 1970-01-01
    • 2012-04-09
    • 2019-03-29
    相关资源
    最近更新 更多