【问题标题】:Pandas to_datetime no error on wrong formatPandas to_datetime 格式错误没有错误
【发布时间】:2020-02-29 19:49:21
【问题描述】:

我读入了一个包含日期的 CSV 文件。有些日期的格式可能错误,我想找到那些。通过以下方法,我会预计第二行是NaT。但是无论我设置infer_datetime_format还是exact,pandas似乎都忽略了指定的格式。

import pandas as pd
from io import StringIO

DATA = StringIO("""date
2019 10 07
   2018 10
""")
df = pd.read_csv(DATA)

df['date'] = pd.to_datetime(df['date'], format="%Y %m %d", errors='coerce', exact=True)

结果

        date
0 2019-10-07
1 2018-10-01

pandas.to_datetime 文档引用了strftime() and strptime() Behavior,但是当我使用纯 Python 对其进行测试时,它可以工作:

datetime.datetime.strptime('  2018 10', '%Y %m %d')

我得到期望值错误:

ValueError: time data '  2018 10' does not match format '%Y %m %d'

我错过了什么?

仅供参考:这个问题pandas to_datetime not working 似乎是相关的,但有所不同,现在似乎已修复。它适用于我的熊猫版本 0.25.2。

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    这是一个已知的错误,详情请参阅github

    由于我们需要一个解决方案,我想出了以下解决方法。请注意,在我的问题中,我使用了read_csv 来保持可重现的代码 sn-p 小而简单。我们实际上使用read_fwf,这里是一些示例数据(time.txt):

    2019 10 07 + 14:45 15:00  # Foo
    2019 10 07 + 18:00 18:30  # Bar
      2019 10 09 + 13:00 13:45  # Wrong indentation
    

    我觉得说明行号也是一个好主意,所以我添加了一点伏都教:

    class FileSanitizer(io.TextIOBase):
        row = 0
        date_range = None
    
        def __init__(self, iterable, date_range):
            self.iterable = iterable
            self.date_range = date_range
    
        def readline(self):
            result = next(self.iterable)
            self.row += 1
            try:
                datetime.datetime.strptime(result[self.date_range[0]:self.date_range[1]], "%Y %m %d")
            except ValueError as excep:
                raise ValueError(f'row: {self.row} => {str(excep)}') from ValueError
            return result
    
    
    filepath = 'time.txt'
    colspecs = [[0, 10], [13, 18], [19, 25], [26, None]]
    names = ['date', 'start', 'end', 'description']
    
    with open(filepath, 'r') as file:
        df = pd.read_fwf(FileSanitizer(file, colspecs[0]),
                         colspecs=colspecs,
                         names=names,
                         )
    

    解决方案基于此答案How to skip blank lines with read_fwf in pandas?。请注意,这将适用于read_csv

    现在我按预期收到以下错误:

    ValueError: row: 3 => time data '  2019 10 ' does not match format '%Y %m %d'
    

    如果有人有更复杂的答案,我很乐意学习。

    【讨论】:

      猜你喜欢
      • 2023-02-10
      • 2019-04-19
      • 2018-02-13
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2017-02-20
      • 2021-11-02
      • 2018-10-06
      相关资源
      最近更新 更多