简体   繁体   English

Python日期时间模式匹配

[英]Python datetime pattern matching

I'm trying to identify if a string can be cast as a date, according to a list of different formats. 我试图根据不同格式的列表来确定是否可以将字符串转换为日期。 Thus, the whole list has to be looped over. 因此,必须遍历整个列表。 If a match is found, that match should be returned. 如果找到匹配项,则应返回该匹配项。 If all attempts return errors, that error should be returned. 如果所有尝试均返回错误,则应返回该错误。 I'm not quite sure how to do this, my approach can be seen below. 我不太确定该怎么做,我的方法如下所示。

_DEFAULT_PATTERNS = ["%d.%m.%Y", "%y-%m-%d"]
try:
    if format == 'default':
        for p in _DEFAULT_PATTERNS:
        try:
            value = datetime.strptime(value, p).date()
        except:
            continue
except Exception:
    return ERROR

return value

Your first choice would be to use dateutil.parser . 您的首选是使用dateutil.parser If, however, the parser does not meet your needs, here's a version of your code, tidied up: 但是,如果解析器不能满足您的需求,请整理以下代码版本:

def parseDate(value):
    PATTERNS = ("%d.%m.%Y", "%y-%m-%d")
    for p in PATTERNS:
        try:
            return datetime.strptime(value, p).date()
        except ValueError:
            continue
    return False # No match found

Alternatively, raise an exception if the match is not found (instead of returning False ). 或者,如果找不到匹配项,则引发异常(而不是返回False )。 This will make your function more similar to strptime : 这将使您的功能更类似于strptime

    raise ValueError

Try something like this: 尝试这样的事情:

from datetime import datetime
_DEFAULT_PATTERNS = ["%d.%m.%Y", "%y-%m-%d"]
def is_castable_to_date(value):
    for p in _DEFAULT_PATTERNS:
        try:
            value = datetime.strptime(value, p).date()
            return True
        except:
            pass
    return False
print is_castable_to_date("12-12-12")
print is_castable_to_date("12.12.12")
print is_castable_to_date("12/12/12")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM