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

user541686 picture user541686 · Jul 7, 2011 · Viewed 24.3k times · Source

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.

Answer

SingleNegationElimination picture SingleNegationElimination · Jul 8, 2011

If you don't want the exception, catch the exception.

try:
    d = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
except ValueError:
    d = None

In the zen of Python, explicit is better than implicit. strptime always returns a datetime parsed in the exact format specified. This makes sense, because you have to define the behavior in case of failure, maybe what you really want is.

except ValueError:
    d = datetime.datetime.now()

or

except ValueError:
    d = datetime.datetime.fromtimestamp(0)

or

except ValueError:
    raise WebFramework.ServerError(404, "Invalid date")

By making it explicit, it's clear to the next person who reads it what the failover behavior is, and that it is what you need it to be.


Or maybe you're confident that the date cannot be invalid; it's coming from a database DATETIME, column, in which case there won't be an exception to catch, and so don't catch it.