Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Validate String date format
Next article icon

Python – Extract date in String

Last Updated : 23 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Method #3: Using string manipulation

Approach

We can use string manipulation to search for the date format string in the input string.

Algorithm

1. Split the input string into words.
2. Iterate through the words and check if each word matches the date format string.
3. If a match is found, return the date format string.

Python3

test_str = "gfg at 2021-01-04"
 
# Split the input string into words and iterate through them
words = test_str.split()
for word in words:
    if len(word) == 10 and word[4] == "-" and word[7] == "-":
        print(word)
        break
                      
                       

Output
2021-01-04

Time complexity: O(n)
Auxiliary Space: O(1)

METHOD 4:Using Split and Join

APPROACH:

This approach first splits the string into a list of words, then extracts the last word which is the date, and finally splits the date using ‘-‘ and joins it again using ‘-‘.

ALGORITHM:

1.Split the input string by space character, which gives a list of two elements: the text “gfg” and the date string “2021-01-04”.
2.Get the last element of the list (i.e., the date string) using indexing.
3.Split the date string by “-” character, which gives a list of three elements: the year, month, and day.
4.Join the elements of the list with “-” character using the join() method to get the final date string.

Python3

string = 'gfg at 2021-01-04'
date = "-".join(string.split()[-1].split("-"))
print("Computed date:", date)
                      
                       

Output
Computed date: 2021-01-04

Time complexity: O(n), where n is the length of the string.
Space complexity: O(n).

METHOD 5:Using Regular Expression

APPROACH:

The program extracts the date from a given string using regular expression.

ALGORITHM:

1.Import the re module.
2.Define the input string.
3.Use the re.findall() method with a regular expression pattern to extract the date from the string.
4.Print the extracted date.

Python3

import re
 
string = 'gfg at 2021-01-04'
 
date = re.findall('\d{4}-\d{2}-\d{2}', string)[0]
 
print("Computed date:", date)
                      
                       

Output
Computed date: 2021-01-04 

Time Complexity: The time complexity of the program depends on the size of the input string and the efficiency of the regular expression pattern. In the worst case, the time complexity is O(n), where n is the length of the input string.

Space Complexity: The space complexity of the program is O(1), as it only stores the extracted date in a variable.



Next Article
Python - Validate String date format
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python datetime-program
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Extract String till Numeric
    Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
    5 min read
  • Python | Extract words from given string
    In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
    5 min read
  • Python - Validate String date format
    Given a date format and a string date, the task is to write a python program to check if the date is valid and matches the format. Examples: Input : test_str = '04-01-1997', format = "%d-%m-%Y" Output : True Explanation : Formats match with date. Input : test_str = '04-14-1997', format = "%d-%m-%Y"
    3 min read
  • Extract substrings between brackets - Python
    Extract substrings between bracket means identifying and retrieving portions of text that are enclosed within brackets. This can apply to different types of brackets like (), {}, [] or <>, depending on the context. Using regular expressions Regular expressions are the most efficient way to ext
    3 min read
  • Python - Extract string between two substrings
    The problem is to extract the portion of a string that lies between two specified substrings. For example, in the string "Hello [World]!", if the substrings are "[" and "]", the goal is to extract "World". If the starting or ending substring is missing, handle the case appropriately (e.g., return an
    3 min read
  • Python Extract Substring Using Regex
    Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
    2 min read
  • Python - Extract String after Nth occurrence of K character
    Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
    7 min read
  • Python | Sort list of dates given as strings
    To sort a list of dates given as strings in Python, we can convert the date strings to datetime objects for accurate comparison. Once converted, the list can be sorted using Python's built-in sorted() or list.sort() functions. This ensures the dates are sorted chronologically. Using pandas.to_dateti
    3 min read
  • Python - Remove after substring in String
    Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
    3 min read
  • Get Current time in Python
    In this article, we will know the approaches to get the current time in Python. There are multiple ways to get it. The most preferably date-time module is used in Python to create the object containing date and time. DateTime object in Python is used to manage operations involving time-based data. d
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences