如何检查日期时间是否存在于 Python 的给定时区?

How to check that a datetime exists in a given timezone in Python?

我需要读取以 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'))

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