Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making the dateutil parser raise errors for ambiguous dates

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>
like image 370
tehsockz Avatar asked Aug 03 '13 03:08

tehsockz


People also ask

What is dateutil parser?

The parser module can parse datetime strings in many more formats. There can be no better library than dateutil to parse dates and times in Python. To lookup the timezones, the tz module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects.

Is dateutil built into Python?

Introduction to Python dateutil. In this article, we will discuss an in-built Python module dateutil. In Python, dateutil is an extension module of the datetime module which is used for displaying the date and time.

Is dateutil included in Python 3?

The dateutil is a third-party module. It has as of late been ported to Python 3 with dateutil 2.0, and the parser functions were ported also. So the substitution is dateutil.


1 Answers

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)
like image 129
Eric Pauley Avatar answered Oct 07 '22 05:10

Eric Pauley