Extract Date from String to DateTime Object

  • Share this:

Code introduction


This function extracts a date from a given string that matches the format YYYY-MM-DD and returns a datetime object. If the string does not contain a date in the correct format, it raises a ValueError exception.


Technology Stack : Regular expressions (re), datetime

Code Type : Date extraction function

Code Difficulty : Intermediate


                
                    
import datetime
import re

def extract_date_from_string(date_string):
    """
    从字符串中提取日期并返回datetime对象。
    """
    pattern = r'\d{4}-\d{2}-\d{2}'
    match = re.search(pattern, date_string)
    if match:
        return datetime.datetime.strptime(match.group(), '%Y-%m-%d')
    else:
        raise ValueError("日期字符串格式不正确")