fuzzy
参数用于此目的:将其用于
dateutil
。
from dateutil.parser import parse
string = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five."
dt = parse(string, fuzzy=True)
结果如下:
datetime.datetime(2014, 12, 4, 4, 7, 59)
如果你只想要日期,只需使用
dt.date()
返回一个日期对象。
请注意,如果字符串中还有其他可能是日期的元素(例如单词“March”等),这会对解析器造成问题。
如果你想查看它跳过的内容,请使用
fuzzy_with_tokens
:
from dateutil.parser import parse
string = "2014-12-04 04:07:59 <font color='green'> info:</font> One, two, three, four, five."
dt = parse(string, fuzzy=True)
dt, tokens = parse(string, fuzzy_with_tokens=True)
tokens
的解析结果为:
(' ', " <font color='green'> info:</font> One, two, three, four, five.")
datetime.strptime(string.partition(' ')[0], '%Y-%m-%d'))
以外,你是指什么?实际上你需要挑选出一个可能的日期候选项(如果有多个怎么办,更不用说不同的格式了),然后对其进行解析。 - Jon Clementsdateutil
可以帮助解析各种格式的日期,但是您传递给它的字符串仍然需要看起来像一个日期。我认为它不会查找字符串中类似日期的内容并尝试解析。 - mgilsonfuzzy
忽略字符串中所有看起来不像日期的内容。 - Paul