Question

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>
Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top