How to extract date from a string in Python?

PythonServer Side ProgrammingProgramming

You need to know the format of date that can be there in the string in order to extract it. You can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date. For example, If you have the date in a string in the format YYYY-MM-DD, you can use the following code to extract and parse this date,

Example

import re, datetime
s = "I have a meeting on 2018-12-10 in New York"
match = re.search('\d{4}-\d{2}-\d{2}', s)
date = datetime.datetime.strptime(match.group(), '%Y-%m-%d').date()
print date

Output

This will give the output −

2018-12-10
raja
Published on 14-Dec-2017 09:30:01
Advertisements