Python 如何从字符串中提取日期
在本文中,我们将了解如何在Python中从字符串中提取日期。
第一种技术使用正则表达式。导入re库并安装(如果尚未安装),以便使用它。在导入re库后,我们可以使用正则表达式” \d{4}-\d{2}-\d{2} “。
要从字符串中提取日期,首先必须了解日期的格式。为了提取日期,只需使用正则表达式和”datetime.datetime.strptime”进行解析。例如,如果在字符串中有一个格式为” YYYY−MM−DD “的日期,您可以使用下面的代码提取和解析它。
示例
在下面给出的示例中,我们将一个字符串作为输入,并尝试使用正则表达式找出字符串中存在的日期。
import re, datetime
str1 = "My Date of Birth is 2006-11-12"
print("The given string is")
print(str1)
day = re.search('\d{4}-\d{2}-\d{2}', str1)
date = datetime.datetime.strptime(day.group(), '%Y-%m-%d').date()
print("The date present in the string is")
print(date)
输出
上述示例的输出如下所示−
The given string is
My Date of Birth is 2006-11-12
The date present in the string is
2006-11-12
使用dateutil()模块
第二种方法是使用dateutil()库的解析器类的解析方法。该方法返回字符串中的任何日期。我们应该发送一个参数fuzzy,并将其设置为True,格式应该是的形式。该方法计算字符串中的日期并将其作为输出返回。
示例
在下面的示例中,我们输入一个字符串,并尝试查找它是否包含任何日期。
from dateutil import parser
str1 = "My Date of Birth is 2006-11-12"
print("The given string is")
print(str1)
date = parser.parse(str1, fuzzy=True)
print("The date present in the string is")
print(str(date)[:10])
输出
以上示例的输出如下所示:
The given string is
My Date of Birth is 2006-11-12
The date present in the string is
2006-11-12