Making the dateutil parser raise errors for ambiguous dates
Asked Answered
C

1

5

dateutil.parser is used to parse a given string and convert it to a datetime.datetime object. It handles ambiguous dates, like "2-5-2013," by allowing dayfirst and yearfirst parameters to give precedent to a certain format.

Is it possible to have the parser raise an error if it encounters an ambiguous date? I imagine it would require modifying the source code (parser.py) around lines 675/693/696, but if there's a way that doesn't require literally editing the source code and instead just involves redefining certain functions, that'd be great as well.

Current behavior:

>>> from dateutil import parser
>>> parser.parse("02-03-2013")
datetime.datetime(2013, 2, 3, 0, 0)

Desired behavior:

>>> from dateutil import parser
>>> parser.parse("02-03-2013")
Traceback (most recent call last):
..
ValueError: The date was ambiguous...<some text>
Cheadle answered 3/8, 2013 at 3:50 Comment(1)
Can you monkey-patch the parse-method?Sahara
P
10

The best way to do this is probably to write a method that checks the equality of the 3 different ambiguous cases:

from dateutil import parser

def parse(string, agnostic=True, **kwargs):
    if agnostic or parser.parse(string, **kwargs) == parser.parse(string, yearfirst=True, **kwargs) == parser.parse(string, dayfirst=True, **kwargs):
        return parser.parse(string, **kwargs)
    else:
        raise ValueError("The date was ambiguous: %s" % string)
Pamplona answered 3/8, 2013 at 4:2 Comment(3)
That's such a natural -- yet effective -- way to do it; I'm very impressed (and shamed that I didn't think of it myself). Thanks!Cheadle
I think this is the correct logic as well. To add to this, if you only want certain datetimes to be considered unacceptable, then change the conditional's logic to match exactly what is acceptable.Compassion
I added in a bit more login to allow disabling of this check as well as forwarding the keyword arguments.Pamplona

© 2022 - 2024 — McMap. All rights reserved.