Python 是否有相当于 C# 的 DateTime.TryParse() 的函数?

发布于 2024-11-19 05:44:09 字数 100 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

爱你是孤单的心事 2024-11-26 05:44:09

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

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

在 Python 的禅宗中,显式优于隐式。 strptime 始终返回以指定的确切格式解析的日期时间。这是有道理的,因为你必须定义失败时的行为,也许你真正想要的是。

except ValueError:
    d = datetime.datetime.now()

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

except ValueError:
    raise WebFramework.ServerError(404, "Invalid date")

通过使其明确,下一个阅读它的人会清楚故障转移行为是什么,并且这就是您所需要的。


或者您确信该日期不会无效;它来自数据库 DATETIME 列,在这种情况下不会有异常需要捕获,因此不要捕获它。

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

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

or

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

or

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.


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.

雪花飘飘的天空 2024-11-26 05:44:09

我们想要尝试...捕获多种日期时间格式fmt1,fmt2,...,fmtn并抑制/处理异常(来自strptime )对于所有不匹配的情况(特别是避免需要一个由 try..catch 子句组成的令人讨厌的 n 深缩进梯子)。我发现了两种优雅的方法,第二个通常是最好的。 (这对于现实世界的数据来说是一个大问题,其中多个、不匹配、不完整、不一致和多语言/区域日期格式经常在一个数据集中自由混合。)

1)单独尝试应用每种格式并处理每个单独的strptime() 由于返回值 None 而失败,因此您可以链接 fn 调用...

首先,改编自 @OrWeis 的紧凑性答案:

def try_strptime_single_format(s, fmt):
    try:
        return datetime.datetime.strptime(s, fmt)
    except ValueError:
        return None

现在你可以调用为try_strptime(s, fmt1) 或 try_strptime(s, fmt2) 或 try_strptime(s, fmt3) ... 但我们可以将其改进为:

2) 应用多种可能的格式(或者传入作为参数或使用合理的默认值),迭代这些,捕获并在内部处理任何错误:

formats 参数可以是单个字符串或列表,然后对其进行迭代...因此您的调用减少为 try_strptime(s, [fmt1, fmt2, fmt3, ...])

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None # or reraise the ValueError if no format matched, if you prefer

(作为侧边栏,请注意 ...finally 不是我们想要的 droid,因为它会在每个候选格式上的每个循环传递后执行,而不是在循环结束时执行一次。 )

我找到实现2)更干净、更好。特别是,该函数/方法可以存储默认格式的列表,这使得它在实际数据上更加安全,并且更少出现异常。 (我们甚至可以根据其他列推断要应用哪些默认格式,例如首先尝试德国数据上的德语日期格式、阿拉伯语上的阿拉伯语、博客数据上的博客日期时间格式等。)

We want to try...catch multiple datetime formats fmt1,fmt2,...,fmtn and suppress/handle the exceptions (from strptime) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder of try..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 of None, so you can chain fn calls...

To start off, adapting from @OrWeis' answer for compactness:

def try_strptime_single_format(s, fmt):
    try:
        return datetime.datetime.strptime(s, fmt)
    except ValueError:
        return None

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 to try_strptime(s, [fmt1, fmt2, fmt3, ...])

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
        try:
            return datetime.strptime(s, fmt)
        except:
            continue

    return None # or reraise the ValueError if no format matched, if you prefer

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

一曲琵琶半遮面シ 2024-11-26 05:44:09

不,你要求的不是惯用的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).

分分钟 2024-11-26 05:44:09

这是一个等效的函数实现

import datetime

def try_strptime(s, format):
    """
    @param s the string to parse
    @param format the format to attempt parsing of the given string
    @return the parsed datetime or None on failure to parse 
    @see datetime.datetime.strptime
    """
    try:
        date = datetime.datetime.strptime(s, format)
    except ValueError:
        date = None
    return date

Here's an equivalent function implementation

import datetime

def try_strptime(s, format):
    """
    @param s the string to parse
    @param format the format to attempt parsing of the given string
    @return the parsed datetime or None on failure to parse 
    @see datetime.datetime.strptime
    """
    try:
        date = datetime.datetime.strptime(s, format)
    except ValueError:
        date = None
    return date
我们只是彼此的过ke 2024-11-26 05:44:09

蛮力也是一种选择:

def TryParse(datestring, offset):
    nu = datetime.datetime.now()
    retval = nu
    formats = ["%d-%m-%Y","%Y-%m-%d","%d-%m-%y","%y-%m-%d"]  

    if datestring == None:
        retval = datetime.datetime(nu.year,nu.month,nu.day,0,0,0) - datetime.timedelta(offset,0,0,0,0,0,0)
    elif datestring == '':
        retval = datetime.datetime(nu.year,nu.month,nu.day,0,0,0) - datetime.timedelta(offset,0,0,0,0,0,0) 
    else:
        succes = False
        for aformat in formats:
            try:
                retval = datetime.datetime.strptime(datestring,aformat)
                succes = True
                break
            except:
                pass
        if not succes:
            retval = datetime.datetime(nu.year,nu.month,nu.day,0,0,0) - datetime.timedelta(offset,0,0,0,0,0,0) 
    return retval

Brute force is also an option:

def TryParse(datestring, offset):
    nu = datetime.datetime.now()
    retval = nu
    formats = ["%d-%m-%Y","%Y-%m-%d","%d-%m-%y","%y-%m-%d"]  

    if datestring == None:
        retval = datetime.datetime(nu.year,nu.month,nu.day,0,0,0) - datetime.timedelta(offset,0,0,0,0,0,0)
    elif datestring == '':
        retval = datetime.datetime(nu.year,nu.month,nu.day,0,0,0) - datetime.timedelta(offset,0,0,0,0,0,0) 
    else:
        succes = False
        for aformat in formats:
            try:
                retval = datetime.datetime.strptime(datestring,aformat)
                succes = True
                break
            except:
                pass
        if not succes:
            retval = datetime.datetime(nu.year,nu.month,nu.day,0,0,0) - datetime.timedelta(offset,0,0,0,0,0,0) 
    return retval
以可爱出名 2024-11-26 05:44:09

使用 time.strptime 解析字符串中的日期。

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

示例来自:http://pleac.sourceforge.net/pleac_python/datesandtimes.html

#----------------------------- 
# Parsing Dates and Times from Strings

time.strptime("Tue Jun 16 20:18:03 1981")
# (1981, 6, 16, 20, 18, 3, 1, 167, -1)

time.strptime("16/6/1981", "%d/%m/%Y")
# (1981, 6, 16, 0, 0, 0, 1, 167, -1)
# strptime() can use any of the formatting codes from time.strftime()

# The easiest way to convert this to a datetime seems to be; 
now = datetime.datetime(*time.strptime("16/6/1981", "%d/%m/%Y")[0:5])
# the '*' operator unpacks the tuple, producing the argument list.

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

#----------------------------- 
# Parsing Dates and Times from Strings

time.strptime("Tue Jun 16 20:18:03 1981")
# (1981, 6, 16, 20, 18, 3, 1, 167, -1)

time.strptime("16/6/1981", "%d/%m/%Y")
# (1981, 6, 16, 0, 0, 0, 1, 167, -1)
# strptime() can use any of the formatting codes from time.strftime()

# The easiest way to convert this to a datetime seems to be; 
now = datetime.datetime(*time.strptime("16/6/1981", "%d/%m/%Y")[0:5])
# the '*' operator unpacks the tuple, producing the argument list.
无法回应 2024-11-26 05:44:09

我同意 tryparse 是 c# 上非常有用的函数。不幸的是,Python 中没有等效的直接函数(可能我不知道)。我相信您想检查字符串是否为日期而不用担心日期格式。我的建议是使用 pandas to_datetime 函数:

def is_valid_date(str_to_validate: str) -> bool:
    try:
        if pd.to_datetime(str_to_validate):
            return True
        else:
            return False
    except ValueError:
        return False

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:

def is_valid_date(str_to_validate: str) -> bool:
    try:
        if pd.to_datetime(str_to_validate):
            return True
        else:
            return False
    except ValueError:
        return False
骑趴 2024-11-26 05:44:09

strptime 怎么样?

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

如果无法根据提供的格式解析字符串,它将抛出 ValueError 。


编辑:

由于在我回答后问题被编辑以包含有关异常的部分。我想对此添加一条注释。

正如其他答案中所指出的,如果您不希望程序引发异常,您可以简单地捕获它并处理它:

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

这是一种执行您想要的操作的 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文