gpt4 book ai didi

python - 从 CET/CEST 到 UTC 的时间序列转换

转载 作者:行者123 更新时间:2023-12-04 17:07:31 25 4
gpt4 key购买 nike

我有两个时间序列文件,它们应该在 CET/CEST 中。其中不好的一个,没有以正确的方式写入值。对于好的 csv,请参见此处:

#test_good.csv
local_time,value
...
2017-03-26 00:00,2016
2017-03-26 01:00,2017
2017-03-26 03:00,2018
2017-03-26 04:00,2019
...
2017-10-29 01:00,7224
2017-10-29 02:00,7225
2017-10-29 02:00,7226
2017-10-29 03:00,7227
...

...一切正常使用:

        df['utc_time'] = pd.to_datetime(df[local_time_column])
.dt.tz_localize('CET', ambiguous="infer")
.dt.tz_convert('UTC').dt.strftime('%Y-%m-%d %H:%M:%S')

将 test_bad.csv 转换为 UTC 时,我收到 AmbiguousTimeError,因为缺少 10 月的 2 小时。

# test_bad.csv
local_time,value
...
2017-03-26 00:00,2016
2017-03-26 01:00,2017 # everything is as it should be
2017-03-26 03:00,2018
2017-03-26 04:00,2019
...
2017-10-29 01:00,7223
2017-10-29 02:00,7224 # the value of 2 am should actually be repeated PLUS 3 am is missing
2017-10-29 04:00,7226
2017-10-29 05:00,7227
...

有谁知道如何将时间序列文件转换为 UTC 并为新索引中的缺失日期添加 NaN 列的优雅方法?感谢您的帮助。

最佳答案

详细阐述 Mark Ransom 的评论;

2017-10-29 02:00,7224 

是模棱两可的;它可能是 2017-10-29 00:00 UTC 2017-10-29 01:00 UTC .这就是为什么 pd.to_datetime 拒绝推断任何东西。

借助一些 native Python,您可以解决这个问题。假设您只是将 csv 加载到 df 而没有将任何内容解析到 datetime,您可以像这样继续

from datetime import datetime
import pytz

df['local_time'] = [pytz.timezone('Europe/Berlin').localize(datetime.fromisoformat(t)) for t in df['local_time']]

# so you can make a UTC index:
df.set_index(df['local_time'].dt.tz_convert('UTC'), inplace=True)

# Now you can create a new, hourly index from that and re-index:
dti = pd.date_range(df.index[0], df.index[-1], freq='H')
df2 = df.reindex(dti)

# for comparison, the "re-created" local_time column:
df2['local_time'] = df2.index.tz_convert('Europe/Berlin').strftime('%Y-%m-%d %H:%M:%S').values

那应该给你类似的东西

df2
value local_time
2017-03-25 23:00:00+00:00 2016.0 2017-03-26 00:00:00
2017-03-26 00:00:00+00:00 2017.0 2017-03-26 01:00:00
2017-03-26 01:00:00+00:00 2018.0 2017-03-26 03:00:00
2017-03-26 02:00:00+00:00 2019.0 2017-03-26 04:00:00
2017-03-26 03:00:00+00:00 NaN 2017-03-26 05:00:00
... ...
2017-10-29 00:00:00+00:00 NaN 2017-10-29 02:00:00
2017-10-29 01:00:00+00:00 7224.0 2017-10-29 02:00:00 # note: value randomly attributed to "second" 2 am
2017-10-29 02:00:00+00:00 NaN 2017-10-29 03:00:00
2017-10-29 03:00:00+00:00 7226.0 2017-10-29 04:00:00
2017-10-29 04:00:00+00:00 7227.0 2017-10-29 05:00:00

如上所述,值 7224 归因于 2017-10-29 01:00:00 UTC,但它也可以归因于 2017-10-29 00:00:00 UTC 如果你不在乎,那很好。如果这是一个问题,我认为你能做的最好的事情就是放弃这个值(value)。您可以使用

df['local_time'] = pd.to_datetime(df['local_time']).dt.tz_localize('Europe/Berlin', ambiguous='NaT')

而不是上面代码中的原生 Python 部分。

关于python - 从 CET/CEST 到 UTC 的时间序列转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70235068/

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