在Python中从字符串提取日期
我该怎么从像“猴子 2010-07-10 爱香蕉”这样的字符串中提取出日期呢?谢谢!
8 个回答
40
如果你想从字符串中提取日期,Python里最好用的模块就是datefinder模块。
你可以按照下面简单的步骤在你的Python项目中使用它。
步骤 1:安装 datefinder 包
pip install datefinder
步骤 2:在你的项目中使用它
import datefinder
input_string = "monkey 2010-07-10 love banana"
# a generator will be returned by the datefinder module. I'm typecasting it to a list. Please read the note of caution provided at the bottom.
matches = list(datefinder.find_dates(input_string))
if len(matches) > 0:
# date returned will be a datetime.datetime object. here we are only using the first match.
date = matches[0]
print date
else:
print 'No dates found'
注意:如果你预计会有很多匹配的结果,那么把结果转换成列表的方式就不太推荐了,因为这样会影响性能,变得比较慢。
195
使用 python-dateutil:
In [1]: import dateutil.parser as dparser
In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)
无效的日期会引发一个 ValueError
错误:
In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month
它可以识别多种格式的日期:
In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)
注意,如果日期不明确,它会进行猜测:
In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)
不过,处理模糊日期的方式是可以自定义的:
In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)
120
如果日期是以固定的格式给出的,你可以直接用一种叫做“正则表达式”的工具来提取日期,然后用“datetime.datetime.strptime”这个方法来解析日期。
import re
from datetime import datetime
match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()
但是,如果日期是以任意的格式给出的,那就不容易提取了。