Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Extract date in String

  • Last Updated : 09 May, 2021

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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
Recommended Articles
Page :

Start Your Coding Journey Now!