DateTime.TryParse()在Python中? [英] DateTime.TryParse() in Python?

查看:160
本文介绍了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.

这篇关于DateTime.TryParse()在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆