How to catch DateParseError in pandas?

180 Views Asked by At

I am running a script that uses pd.to_datetime() on inputs that are sometime not able to be parsed.

For example if I try to run pd.to_datetime('yesterday') it results to an error

DateParseError: Unknown datetime string format, unable to parse: yesterday, at position 0

I 'd like to catch this exception and process it further in my code.

I have tried:

try:
    pd.to_datetime('yesterday')
except pd.errors.ParserError:
    print('exception caught')

but the exception is not caught. Does anyone know where DateParseError is defined and how I can catch it? Searching in pandas documentation doesn't yield any results

1

There are 1 best solutions below

0
mozway On BEST ANSWER

You can import it from pandas._libs.tslibs.parsing:

from pandas._libs.tslibs.parsing import DateParseError

try:
    pd.to_datetime('yesterday')
except DateParseError:
    print('exception caught')