Computer >> Computer tutorials >  >> Programming >> Python

How to extract date from a string in Python?


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