How to extract date from a string in Python?

PythonServer Side ProgrammingProgramming

In this article, we are going to find out how to extract a date from a string in Python.

Regular expressions are used in the first technique. Import the re library and install it if it isn't already installed to use it. After importing the re library, we can use the regular expression "\d{4}-\d{2}-\d{2}".

To extract a date from a string, you must first understand the format of the date. To extract the date, simply use a regular expression and "datetime.datetime.strptime" to parse it. For example, if you have a date in the format YYYY−MM−DD in a string, you may extract and parse it using the code below.

Example

In the example given below, we are taking a string as input and we are trying to find out the date present in the string using the Regular Expressions 

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)

Output

The output of the above example is as shown below −

The given string is
My Date of Birth is 2006-11-12
The date present in the string is
2006-11-12

Using dateutil() module

The second approach is by using the parse method of parser class of dateutil() library. This method returns any date present in a string. We should send a parameter fuzzy and set it as True and the format should be of the form YYYY−MM−DD. This method computes the date present in a string and returns it as output.

Example

In the example given below, we are taking a string as input and we are trying to find out if it has any date present inside it 

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])

Output

The output of the above example is given below −

The given string is
My Date of Birth is 2006-11-12
The date present in the string is
2006-11-12
raja
Updated on 07-Dec-2022 10:01:57

Advertisements