【发布时间】:2019-11-07 11:50:49
【问题描述】:
我看过一些关于识别可能的字符串是否是日期的帖子,但似乎没有一个帖子涉及句子中是否有潜在的日期。
我使用了 dateutil 解析器函数,它似乎只有在日期是字符串的唯一组成部分时才能有效识别字符串中的日期。
from dateutil.parser import parse
def is_date(string, fuzzy=False):
"""
Return whether the string can be interpreted as a date.
:param string: str, string to check for date
:param fuzzy: bool, ignore unknown tokens in string if True
"""
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False
>>> is_date("1990-12-1")
True
>>> is_date("foo 1990-12-1 bar")
False
【问题讨论】: