pythonpandaspython-datetime

How to catch DateParseError in pandas?


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


Solution

  • 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')