Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 818
user541686 Avatar asked Jul 07 '11 18:07

user541686


People also ask

Can Python be used instead of C?

Ease of development – Python has fewer keywords and more free English language syntax whereas C is more difficult to write. Hence, if you want an easy development process go for Python. Performance – Python is slower than C as it takes significant CPU time for interpretation. So, speed-wise C is a better option.

Should I learn C for Python?

In my opinion it's better to start learning Python. I found it easier to learn then C or C++. It has libraries to do virtually anything you might need, and can do essentially anything. The only reason to use a more difficult language like C/C++ is if you need the performance or are writing code for an embedded system.


2 Answers

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.

like image 99
SingleNegationElimination Avatar answered Sep 21 '22 15:09

SingleNegationElimination


We want to try...catch multiple datetime formats fmt1,fmt2,...,fmtn and suppress/handle the exceptions (from strptime) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder of try..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 of None, so you can chain fn calls...

To start off, adapting from @OrWeis' answer for compactness:

def try_strptime_single_format(s, fmt):     try:         return datetime.datetime.strptime(s, fmt)     except ValueError:         return None 

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 to try_strptime(s, [fmt1, fmt2, fmt3, ...])

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):     for fmt in fmts:         try:             return datetime.strptime(s, fmt)         except:             continue      return None # or reraise the ValueError if no format matched, if you prefer 

(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.)

like image 38
smci Avatar answered Sep 21 '22 15:09

smci