Python 是否有相当于 C# 的 DateTime.TryParse() 的函数?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您不想要异常,请捕获异常。
在 Python 的禅宗中,显式优于隐式。
strptime
始终返回以指定的确切格式解析的日期时间。这是有道理的,因为你必须定义失败时的行为,也许你真正想要的是。或
或
通过使其明确,下一个阅读它的人会清楚故障转移行为是什么,并且这就是您所需要的。
或者您确信该日期不会无效;它来自数据库 DATETIME 列,在这种情况下不会有异常需要捕获,因此不要捕获它。
If you don't want the exception, catch the exception.
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.or
or
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.
我们想要
尝试...捕获
多种日期时间格式fmt1,fmt2,...,fmtn
并抑制/处理异常(来自strptime
)对于所有不匹配的情况(特别是避免需要一个由try..catch
子句组成的令人讨厌的 n 深缩进梯子)。我发现了两种优雅的方法,第二个通常是最好的。 (这对于现实世界的数据来说是一个大问题,其中多个、不匹配、不完整、不一致和多语言/区域日期格式经常在一个数据集中自由混合。)1)单独尝试应用每种格式并处理每个单独的
strptime()
由于返回值None
而失败,因此您可以链接 fn 调用...首先,改编自 @OrWeis 的紧凑性答案:
现在你可以调用为
try_strptime(s, fmt1) 或 try_strptime(s, fmt2) 或 try_strptime(s, fmt3) ...
但我们可以将其改进为:2) 应用多种可能的格式(或者传入作为参数或使用合理的默认值),迭代这些,捕获并在内部处理任何错误:
formats
参数可以是单个字符串或列表,然后对其进行迭代...因此您的调用减少为try_strptime(s, [fmt1, fmt2, fmt3, ...])
(作为侧边栏,请注意
...finally
不是我们想要的 droid,因为它会在每个候选格式上的每个循环传递后执行,而不是在循环结束时执行一次。 )我找到实现2)更干净、更好。特别是,该函数/方法可以存储默认格式的列表,这使得它在实际数据上更加安全,并且更少出现异常。 (我们甚至可以根据其他列推断要应用哪些默认格式,例如首先尝试德国数据上的德语日期格式、阿拉伯语上的阿拉伯语、博客数据上的博客日期时间格式等。)
We want to
try...catch
multiple datetime formatsfmt1,fmt2,...,fmtn
and suppress/handle the exceptions (fromstrptime
) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder oftry..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 ofNone
, so you can chain fn calls...To start off, adapting from @OrWeis' answer for compactness:
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 totry_strptime(s, [fmt1, fmt2, fmt3, ...])
(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.)
不,你要求的不是惯用的Python,因此通常不会有像标准库中那样丢弃错误的函数。相关标准库模块记录如下:
http://docs.python.org/library/datetime。 html
http://docs.python.org/library/time.html
解析函数都会在无效输入时引发异常。
然而,正如其他答案所述,为您的应用程序构建一个应用程序并不是非常困难(您的问题被表述为“在Python中”而不是“在Python标准库中”,因此不清楚是否有助于编写这样一个函数“在Python中”是否回答了问题)。
No, what you're asking for is not idiomatic Python, and so there generally won't be functions that discard errors like that in the standard library. The relevant standard library modules are documented here:
http://docs.python.org/library/datetime.html
http://docs.python.org/library/time.html
The parsing functions all raise exceptions on invalid input.
However, as the other answers have stated, it wouldn't be terribly difficult to construct one for your application (your question was phrased "in Python" rather than "in the Python standard library" so it's not clear if assistance writing such a function "in Python" is answering the question or not).
这是一个等效的函数实现
Here's an equivalent function implementation
蛮力也是一种选择:
Brute force is also an option:
使用 time.strptime 解析字符串中的日期。
文档: http://docs.python.org/library/time.html#time .strptime
示例来自:http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Use
time.strptime
to parse dates from strings.Documentation: http://docs.python.org/library/time.html#time.strptime
Examples from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
我同意 tryparse 是 c# 上非常有用的函数。不幸的是,Python 中没有等效的直接函数(可能我不知道)。我相信您想检查字符串是否为日期而不用担心日期格式。我的建议是使用
pandas
to_datetime
函数:I agree tryparse is very useful function on c#. Unfortunately no equivalent direct function of that in python (may be i am not aware). I believe you want to check a string is whether date or not without worrying about date format. My recommendation is go for
pandas
to_datetime
function:strptime 怎么样?
http://docs.python.org/library/time.html#time。 strptime
如果无法根据提供的格式解析字符串,它将抛出 ValueError 。
编辑:
由于在我回答后问题被编辑以包含有关异常的部分。我想对此添加一条注释。
正如其他答案中所指出的,如果您不希望程序引发异常,您可以简单地捕获它并处理它:
这是一种执行您想要的操作的 Pythonic 方式。
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:
That's a Pythonic way to do what you want.