是否有与C#的DateTime.TryParse()等效的Python? [英] Is there a Python equivalent to C#'s DateTime.TryParse()?

查看:101
本文介绍了是否有与C#的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

在zen的Python中,显式要比隐式好. strptime 始终 返回以指定的确切格式解析的日期时间.这是有道理的,因为您必须定义发生故障时的行为,也许您真正想要的是.

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 won't be an exception to catch, and so don't catch it.

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

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