DateTime.TryParse()在Python中?

DateTime.TryParse()在Python中?

问题描述:

在Python中有相当于C#的 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.

如果您不想要异常,请捕获异常。

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

在蟒蛇的禅中,显式比隐含更好。 strptime 始终 返回按指定格式解析的datetime。这是有道理的,因为你必须在发生故障时定义行为,也许你真正想要的是。

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

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

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.

或者也许你确信日期不能无效,它来自数据库DATETIME,列,在这种情况下,不会捕获异常,所以不要抓住它。

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