gpt4 book ai didi

python - 如何检查 Python 中给定时区中是否存在日期时间?

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:54 25 4
gpt4 key购买 nike

我需要读取以 CSV 格式提供给我的数据帧温度数据。 date 列应该是本地化的 Europe/Paris 时区,但数据提供者即使由于夏令时不存在日期时间也会提供数据。所以如果我运行:

import pandas as pd
from io import StringIO
from pytz import timezone

csv_string = StringIO("date;temp\n\
2014-03-29 22:00:00;12,5\n\
2014-03-29 23:00:00;12,4\n\
2014-03-30 00:00:00;10,7\n\
2014-03-30 01:00:00;11,7\n\
2014-03-30 02:00:00;12,4\n\
2014-03-30 03:00:00;12,4\n\
2014-03-30 04:00:00;10,7\n\
2014-03-30 05:00:00;10,4\n\
2014-03-30 06:00:00;9,4")

df = pd.read_csv(csv_string, sep=";", decimal=",")
df["date"] = pd.to_datetime(df["date"], infer_datetime_format=True)
df.set_index("date", inplace=True)
df.index = df.index.tz_localize(timezone('Europe/Paris'))

我得到:pytz.exceptions.NonExistentTimeError: 2014-03-30 02:00:00

我正在寻找一种方法来删除会引发 NonExistentTimeError 的行。我如何使用 pandas、pytz 或其他库测试这些行?

最佳答案

我得到了以下结果:

import pandas as pd
from io import StringIO
from pytz import timezone

csv_string = StringIO("date;temp\n\
2014-03-29 22:00:00;12,5\n\
2014-03-29 23:00:00;12,4\n\
2014-03-30 00:00:00;10,7\n\
2014-03-30 01:00:00;11,7\n\
2014-03-30 02:00:00;12,4\n\
2014-03-30 03:00:00;12,4\n\
2014-03-30 04:00:00;10,7\n\
2014-03-30 05:00:00;10,4\n\
2014-03-30 06:00:00;9,4")

def datetime_exists_in_tz(dt, tz):
try:
dt.tz_localize(tz)
return True
except:
return False

df = pd.read_csv(csv_string, sep=";", decimal=",")
df["date"] = pd.to_datetime(df["date"], infer_datetime_format=True)
df = df.loc[df["date"].apply(datetime_exists_in_tz, tz=timezone('Europe/Paris'))]
df.set_index("date", inplace=True)
df.index = df.index.tz_localize(timezone('Europe/Paris'))

仍然对更优雅、更高效的解决方案持开放态度:)

关于python - 如何检查 Python 中给定时区中是否存在日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47308662/

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