使用dateutil.parser.parse抛出两位数年份日期的ValueError

时间:2016-08-29 00:49:17

标签: python date parsing python-dateutil 2-digit-year

在进行一些数据清理时,我注意到dateutil.parser.parse未能拒绝某个格式错误的日期,认为其中的第一个数字是两位数的年份。这个图书馆可以被强制将两位数年份视为无效吗?

示例:

from dateutil.parser import parse
parse('22-23 February')

输出:

datetime.datetime(2022, 2, 23, 0, 0)

1 个答案:

答案 0 :(得分:3)

我设法通过dateutil.parser.parserinfo参数将自定义parserinfo对象传递给dateutil.parser.parse来解决此问题。幸运的是,dateutil.parser.parserinfo有一个convertyear方法,可以在派生类中重载,以便在年份上执行额外的验证。

from dateutil.parser import parse, parserinfo

class NoTwoDigitYearParserInfo(parserinfo):
    def convertyear(self, year, century_specified=False):
        if year < 100 and not century_specified:
            raise ValueError('Two digit years are not supported.')
        return parserinfo.convertyear(self, year, century_specified)

parse('22-23 February', parserinfo = NoTwoDigitYearParserInfo())

输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/site-packages/dateutil/parser.py", line 1162, in parse
    return parser(parserinfo).parse(timestr, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/dateutil/parser.py", line 552, in parse
    res, skipped_tokens = self._parse(timestr, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/dateutil/parser.py", line 1055, in _parse
    if not info.validate(res):
  File "/usr/local/lib/python3.5/site-packages/dateutil/parser.py", line 360, in validate
    res.year = self.convertyear(res.year, res.century_specified)
  File "<stdin>", line 4, in convertyear
ValueError: Two digit years are not supported.