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>
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With