7

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

2
  • 1
    Side note, it's a shame that 'yesterday' is not understood as a valid timestamp (since 'today' is valid). Commented Jan 29, 2024 at 12:44
  • totally agree with you :) Commented Jan 31, 2024 at 6:57

2 Answers 2

7

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')
Sign up to request clarification or add additional context in comments.

2 Comments

I think it is generally not a good idea to import something from the intestines of a library that is not intended to be part of the (stable) interface. If a library contains names starting with _ they are usually not meant to be imported and this might not work anymore after updating the pandas version. So I guess what would be safer for the poster is @mhh's suggestion below.
@jottbe That's true and I agree that using libraries internals is generally not recommended. That said, I answered the "Does anyone know where DateParseError is defined?" part. Catching ValueError is indeed a good approach, however this inheritance is also not officially defined in the API and nothing suggests that it is a stable behavior.
2

You may want to except ValueError instead.

DateParseError inherits ValueErrorand for some cases, pd.to_datetimethrows ValueError and not DateParseError. For example pd.to_datetime("123")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.