Skip to content
Related Articles

Related Articles

Python – Extract date in String

Improve Article
Save Article
  • Last Updated : 09 May, 2021
Improve Article
Save Article

Given a string, the task is to write a Python program to extract date from it.

Input : test_str = "gfg at 2021-01-04"
Output : 2021-01-04
Explanation : Date format string found.

Input : test_str = "2021-01-04 for gfg"
Output : 2021-01-04
Explanation : Date format string found.

Method #1 : Using re.search() + strptime() methods

In this, the search group for a particular date is fed into search(), and strptime() is used to feed in the format to be searched.

Python3




# Python3 code to demonstrate working of
# Detect date in String
# Using re.search() + strptime()
import re
from datetime import datetime
  
# initializing string
test_str = "gfg at 2021-01-04"
  
# printing original string
print("The original string is : " + str(test_str))
  
# searching string
match_str = re.search(r'\d{4}-\d{2}-\d{2}', test_str)
  
# computed date
# feeding format
res = datetime.strptime(match_str.group(), '%Y-%m-%d').date()
  
# printing result
print("Computed date : " + str(res))

Output:

The original string is : gfg at 2021-01-04
Computed date : 2021-01-04

Method #2: Using python-dateutil() module

This is another way to solve this problem. In this inbuilt Python library python-dateutil, The parse() method can be used to detect date and time in a string. 

Python3




# Python3 code to demonstrate working of
# Detect date in String
# Using python-dateutil()
from dateutil import parser
  
# initializing string
test_str = "gfg at 2021-01-04"
  
# printing original string
print("The original string is : " + str(test_str))
  
# extracting date using inbuilt func.
res = parser.parse(test_str, fuzzy=True)
  
# printing result
print("Computed date : " + str(res)[:10])

Output:

The original string is : gfg at 2021-01-04
Computed date : 2021-01-04

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!