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.
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.
Use
time.strptime
to parse dates from strings.Documentation: http://docs.python.org/library/time.html#time.strptime
Examples from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Here's an equivalent function implementation
Brute force is also an option:
We want to
try...catch
multiple datetime formatsfmt1,fmt2,...,fmtn
and suppress/handle the exceptions (fromstrptime
) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder oftry..catch
clauses). I found two elegant ways, the second is best in general. (This is big problem on real-world data where multiple, mismatched, incomplete, inconsistent and multilanguage/region date formats are often mixed freely in one dataset.)1) Individually try applying each format and handle each individual
strptime()
fail as a return-value ofNone
, so you can chain fn calls...To start off, adapting from @OrWeis' answer for compactness:
Now you can invoke as
try_strptime(s, fmt1) or try_strptime(s, fmt2) or try_strptime(s, fmt3) ...
But we can improve that to:2) Apply multiple possible formats (either pass in as an argument or use sensible defaults), iterate over those, catch and handle any errors internally:
Cleaner, simpler and more OO-friendly is to generalize this to make the
formats
parameter either a single string or a list, then iterate over that... so your invocation reduces totry_strptime(s, [fmt1, fmt2, fmt3, ...])
(As a sidebar, note that
...finally
is not the droid we want, since it would execute after each loop pass i.e. on each candidate format, not once at the end of the loop.)I find implementation 2) is cleaner and better. In particular the function/method can store a list of default formats, which makes it more failsafe and less exception-happy on real-world data. (We could even infer which default formats to apply based on other columns, e.g. first try German date formats on German data, Arabic on Arabic, weblog datetime formats on weblog data etc.)
No, what you're asking for is not idiomatic Python, and so there generally won't be functions that discard errors like that in the standard library. The relevant standard library modules are documented here:
http://docs.python.org/library/datetime.html
http://docs.python.org/library/time.html
The parsing functions all raise exceptions on invalid input.
However, as the other answers have stated, it wouldn't be terribly difficult to construct one for your application (your question was phrased "in Python" rather than "in the Python standard library" so it's not clear if assistance writing such a function "in Python" is answering the question or not).
If you don't want the exception, catch the exception.
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.or
or
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.