Is there a Python equivalent to C#'s DateTime.

2020-03-08 07:29发布

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.

7条回答
SAY GOODBYE
2楼-- · 2020-03-08 08:24

How about strptime?

http://docs.python.org/library/time.html#time.strptime

It will throw a ValueError if it is unable to parse the string based on the format that is provided.


Edit:

Since the question was edited to include the bit about exceptions after I answered it. I wanted to add a note about that.

As was pointed out in other answers, if you don't want your program to raise an exception, you can simply catch it and handle it:

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

That's a Pythonic way to do what you want.

查看更多
登录 后发表回答