Is there a Python equivalent to C#'s DateTime.TryParse()?

Viewed 29297

Is there an equivalent to C#'s DateTime.TryParse() in Python?

I'm referring to the fact that it avoids throwing an exception, not the fact that it guesses the format.

8 Answers

I agree tryparse is very useful function on c#. Unfortunately no equivalent direct function of that in python (may be i am not aware). I believe you want to check a string is whether date or not without worrying about date format. My recommendation is go for pandas to_datetime function:

def is_valid_date(str_to_validate: str) -> bool:
    try:
        if pd.to_datetime(str_to_validate):
            return True
        else:
            return False
    except ValueError:
        return False
Related