Skip to main content
 首页 » 编程设计

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

2025年01月19日13jyk

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

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