【发布时间】:2018-08-10 01:01:36
【问题描述】:
我的字符串具有不同格式的日期。例如,
sample_str_1 = 'this amendment of lease, made and entered as of the 10th day of august, 2016, by and between john doe and jane smith'
另外,还有一个包含日期的字符串,
sample_str_2 ='this agreement, made and entered as of May 1, 2016, between john doe and jane smith'
为了从第一个字符串中提取日期,我做了这样的事情,
match = re.findall(r'\S+d{4}\s+', sample_str_1)
这给出了一个空列表。
对于第二个字符串,我使用与第一个字符串相同的方法并获取一个空字符串。
我也试过datefinder 模块,它给了我这样的输出,
import datefinder
match = datefinder.find_dates(sample_str_1)
for m in match:
print(m)
>> 2016-08-01 00:00:00
以上输出错误,应该是2016-08-10 00:00:00
我尝试了另一种方式使用这个旧的post
match = re.findall(r'\d{2}(?:january|february|march|april|may|june|july|august|september|october|november|december)\d{4}',sample_str_1)
这又给了我一个空列表。
如何从字符串中提取日期?是否有一种通用方法来提取具有文本和数字的日期?任何帮助将不胜感激。
【问题讨论】:
-
也许你应该看看dateparser 包。在这里重新发明轮子没有多大意义……
-
@ctwheels 这没什么,我用
date_parse = DateDataParser().get_date_data(sample_str_1)得到{'date_obj': None, 'locale': None, 'period': 'day'} -
只需要匹配特定短语
[day]st/nd/rd/th day of [month], [year]和[month] [day], [year]吗?还有许多其他方法可以格式化日期。 -
你只有
10th day of august, 2016和May 1, 2016两种格式的日期? -
@CAustin 是的,这是一种格式,而字符串 2 具有不同的格式。
标签: regex string date python-3.5