gpt4 book ai didi

python - 处理 panda to_datetime 函数中的时区

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:37 26 4
gpt4 key购买 nike

已经有很多关于该主题的问题,但我找不到能解决我的麻烦的回复。

<强>1。背景

我将时间戳作为字符串存储在列表中,如下所示:

print(my_timestamps)
...
3 Sun Mar 31 2019 00:00:00 GMT+0100
4 Sun Mar 31 2019 01:00:00 GMT+0100
5 Sun Mar 31 2019 03:00:00 GMT+0200
6 Sun Mar 31 2019 04:00:00 GMT+0200
...
13 Sun Oct 27 2019 01:00:00 GMT+0200
14 Sun Oct 27 2019 02:00:00 GMT+0200
15 Sun Oct 27 2019 02:00:00 GMT+0100
16 Sun Oct 27 2019 03:00:00 GMT+0100
17 Sun Oct 27 2019 04:00:00 GMT+0100
Name: date, dtype: object

您会注意到我保留了 2 个有夏令时的区域。我使用 to_datetime() 将其作为时间戳存储在 panda 数据框中

df['date'] = pd.to_datetime(my_timestamps)
print(df)
...
3 2019-03-31 00:00:00-01:00
4 2019-03-31 01:00:00-01:00
5 2019-03-31 03:00:00-02:00
6 2019-03-31 04:00:00-02:00
...
13 2019-10-27 01:00:00-02:00
14 2019-10-27 02:00:00-02:00
15 2019-10-27 02:00:00-01:00
16 2019-10-27 03:00:00-01:00
17 2019-10-27 04:00:00-01:00
Name: date, dtype: object

(对我来说)第一件令人惊讶的事情是“date”列将其数据类型保持为“object”而不是“datetime64”。

当我想使用这些时间戳作为索引时

df.set_index('date', inplace = True, verify_integrity = True)

我在 verify_integrity 检查时收到错误,通知我存在重复索引。

ValueError: Index has duplicate keys: Index([2019-10-27 02:00:00-01:00, 2019-10-27 03:00:00-01:00], dtype='object', name='date')

我显然想解决这个问题。

<强>2。我尝试过的

我的理解是,不使用时区数据,要使用它,我应该尝试将时间戳转换为“datetime64”。

我首先在 to_datetime 中添加了 utc=True 标志。

test = pd.to_datetime(my_timestamps,utc=True)

但是,我根本不明白结果:

...
3 2019-03-31 01:00:00+00:00
4 2019-03-31 02:00:00+00:00
5 2019-03-31 05:00:00+00:00
6 2019-03-31 06:00:00+00:00
...
13 2019-10-27 03:00:00+00:00
14 2019-10-27 04:00:00+00:00
15 2019-10-27 03:00:00+00:00
16 2019-10-27 04:00:00+00:00
17 2019-10-27 05:00:00+00:00

根据我的理解,时区已经以相反的方式解释了?!

3     Sun Mar 31 2019 00:00:00 GMT+0100

UTC 时间的偏移应为

3     2019-03-30 23:00:00+00:00

但这里它被翻译成:

3    2019-03-31 01:00:00+00:00

这可能解释了出现重复时间戳的错误

14   2019-10-27 04:00:00+00:00
...
16 2019-10-27 04:00:00+00:00

请问,有人知道如何正确处理时区信息,以免导致重复索引吗?

预先感谢您的帮助。

祝你有美好的一天,最好的,

皮埃罗

PS:只要正确管理小时的变化,我就可以使用 UTC 表示的时间戳。

<强>3。编辑

Python 3.7 中的新函数 fromisoformat() 似乎可以提供帮助。但是,它接受字符串作为输入。我不确定如何以“矢量化”方式使用它来将其应用到完整的数据帧列上。

How to convert a timezone aware string to datetime in python without dateutil?

最佳答案

因此,如上所述,dateutil 中确实存在问题。我在原始数据文件中反转了 +/- 符号,如下所示:

How to replace a sub-string conditionally in a pandas dataframe column?

最好的, clown

关于python - 处理 panda to_datetime 函数中的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com