Creating a dateutil parser causes errors for ambiguous dates

dateutil.parser used to parse a given string and convert it to a datetime.datetime object. It handles ambiguous dates, such as "2-5-2013", allowing the dayfirst and yearfirst parameters to use case in a specific format.

Is it possible for the parser to throw an error if it encounters an ambiguous date? I assume that for this you will need to change the source code ( parser.py ) around lines 675/693/696 , but if there is a way that does not require literal editing of the source code and instead simply involves redefining certain functions, this will also be great .

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> 
+4
source share
1 answer

The best way to do this is probably to write a method that checks the equality of three 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) 
+5
source

Source: https://habr.com/ru/post/1495065/


All Articles