python - 将具有多个时区的 pandas 列转换为单个时区

标签 python python-3.x pandas dataframe timezone

问题

我在 pandas DataFrame 中有一个列,其中包含带有时区的时间戳。此列中有两个不同的时区,我需要确保只有一个。这是该列末尾的输出:

260003    2019-05-21 12:00:00-06:00
260004    2019-05-21 12:15:00-06:00
Name: timestamp, Length: 260005, dtype: object

就其值(value)而言,时间戳在 -06:00-07:00 之间变化,并具有以下输出:

datetime.datetime(2007, 10, 1, 1, 0, tzinfo=tzoffset(None, -21600)) for -06:00 datetime.datetime(2007, 11, 17, 5, 15, tzinfo=tzoffset(None, -25200)) for -07:00

我做了什么

我一直在尝试使用 tz.localize 和 tz.convert,它们在过去工作得很好,但我认为数据只有一个时区。例如,如果我这样做:

df['timestamp'].dt.tz_localize('MST', ambigously='infer').dt.tz_convert('MST')

我得到:

ValueError: Array must be all same time zone

During handling of the above exception, another exception occurred:

ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

问题

有没有办法将它们转换为 MST?或者任何时区,真的吗?我想我可以按时区分解 DataFrame(不是 100% 确定如何,但我想这是可能的)并对其进行操作,但我想我会问是否有更智能的解决方案。谢谢!

最佳答案

我尝试过:

df = pd.DataFrame({'timestamp':['2019-05-21 12:00:00-06:00',
                                '2019-05-21 12:15:00-07:00']})
df['timestamp'] = pd.to_datetime(df.timestamp)

df.timestamp.dt.tz_localize('MST')

工作正常并给出:

0   2019-05-21 18:00:00-07:00
1   2019-05-21 19:15:00-07:00
Name: timestamp, dtype: datetime64[ns, MST]

这不是你所期望的吗?

<小时/>

编辑:感谢@G.Anderson 的评论,我尝试了具有时区感知时间戳的不同数据:

df = pd.DataFrame({'timestamp':[pd.to_datetime('2019-05-21 12:00:00').tz_localize('MST'),
                         pd.to_datetime('2019-05-21 12:15:00').tz_localize('EST')]})

然后

df['timestamp'] = pd.to_datetime(df.timestamp)

确实给出了同样的错误。然后我添加了 utc=True:

df.timestamp = pd.to_datetime(df.timestamp, utc=True)

# df.timestamp
# 0   2019-05-21 19:00:00+00:00
# 1   2019-05-21 17:15:00+00:00
# Name: timestamp, dtype: datetime64[ns, UTC]

df.timestamp.dt.tz_convert('MST')

工作正常并给出:

0   2019-05-21 12:00:00-07:00
1   2019-05-21 10:15:00-07:00
Name: timestamp, dtype: datetime64[ns, MST]

关于python - 将具有多个时区的 pandas 列转换为单个时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245036/

相关文章:

python - 读取两行的值并用python写入一行

python - Pandas to_sql 没有在我的表中插入任何数据

python - 如何在 Hangman 游戏中通过一次猜测激活多个字母?

python - 根据列添加缺失的行

pandas - 特征哈希到底是如何工作的?

python - 更改 pandas DataFrame 中日期时间列中的日期

python - 从 XBee 接收的 pySerial 数据未正确显示

python - 从csv文件读取时如何更改列的数据类型

python - django rest framework 如何国际化领域

Python,为每个方法安排一个线程的并行线程