【问题标题】:How to check that a datetime exists in a given timezone in Python?如何在 Python 中检查给定时区中是否存在日期时间?
【发布时间】:2018-04-28 18:03:04
【问题描述】:

我需要读取以 CSV 格式提供给我的数据框温度数据。 datecolumn 应该是本地化的欧洲/巴黎时区,但数据提供者即使由于夏令时不存在日期时间也会提供数据。所以如果我跑:

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 或其他库测试这些行?

【问题讨论】:

    标签: python pandas datetime pytz


    【解决方案1】:

    我最终得到了以下结果:

    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'))
    

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

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2017-01-29
      • 2011-02-07
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 2020-08-14
      • 1970-01-01
      相关资源
      最近更新 更多