关于该主题的问题已经很多,但是我找不到解决我问题的答案。
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
您会注意到我保留了两个具有DST的区域。 我使用to_datetime()将其作为时间戳存储在熊猫数据框中
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
(对我而言)第一个令人惊讶的事情是,“日期”列将其dtype保留为“对象”而不是“ 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。我尝试过的
我的理解是不使用时区数据,要使用它,我应该尝试将时间戳记的dtype转换为“ 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()函数似乎可以提供帮助。但是,它接受字符串作为输入。我不确定如何以“矢量化”方式将其应用于完整的dataframee列。
How to convert a timezone aware string to datetime in python without dateutil?
答案 0 :(得分:0)
因此如上所述的dateutil确实存在问题。 我在原始数据文件中颠倒了+/-号,如下所示:
How to replace a sub-string conditionally in a pandas dataframe column?
最佳, 皮埃罗(Pierrot)