You can download this code by clicking the button below.
This code is now available for download.
This function is used to parse different date format strings and return the corresponding datetime object.
Technology Stack : datetime, re
Code Type : Function
Code Difficulty : Intermediate
import datetime
import re
def parse_date(date_str):
"""
解析日期字符串,并返回datetime对象。
"""
date_patterns = [
(r'\d{4}-\d{2}-\d{2}', '%Y-%m-%d'), # 年-月-日格式
(r'\d{2}/\d{2}/\d{4}', '%m/%d/%Y'), # 月/日/年格式
(r'\d{2}-\d{2}-\d{2}', '%d-%m-%d'), # 日-月-日格式
]
for pattern, format in date_patterns:
if re.match(pattern, date_str):
return datetime.datetime.strptime(date_str, format)
raise ValueError("No valid date format found for: " + date_str)