You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Python dateparser的全部正则表达式以提取日期字符串

Extracting Date Strings from Text with dateparser

Hey there! I get exactly what you're aiming for—you want to pull date-related snippets out of messy input text without maintaining your own regex list, and leverage all the parsing power dateparser already has. Let’s break down the best ways to make this happen:

1. Use dateparser's Built-in search_dates() Function (No Regex Needed!)

This is the simplest, most reliable solution by far. dateparser includes a search_dates() utility that scans your text, extracts every parseable date/time string, and returns them paired with their parsed datetime objects. It’s tailor-made for your use case!

Here’s how to implement it with your example input:

import dateparser
from dateparser.search import search_dates

input_text = "I booked a movie 4 days ago, but planned last week"
# Extract all date strings and their corresponding datetime objects
extracted_dates = search_dates(input_text)

# Loop through results to view the matches
for date_str, dt_obj in extracted_dates:
    print(f"Found date string: '{date_str}' → Parsed to: {dt_obj}")

Sample Output:

Found date string: '4 days ago' → Parsed to: 2024-05-20 16:15:00  # Date depends on current system time
Found date string: 'last week' → Parsed to: 2024-05-13 00:00:00

This method automatically handles every format dateparser supports—including 1 year ago, last 3 mins ago, and dozens more—without you having to write or maintain a single regex pattern yourself.

2. Access dateparser's Internal Regular Expressions

If you really need to review all the regex patterns dateparser uses, you can dig into its open-source source code. Here are the key places to look:

  • Relative time patterns: Check the RelativeTimeParser class in dateparser/parsers/relative_time_parser.py. This includes regex for phrases like X days ago, last week, a month from now, etc.
  • Multilingual date terms: The file dateparser/data/date_translation_data.py contains regex patterns for date-related words (days of the week, months, relative terms) in multiple languages.
  • Time parsing logic: Look in dateparser/parsers/time_parser.py for regex focused on time strings (e.g., 3:45 PM, 14:30).

For example, you’ll find simplified versions of patterns like:

# Matches "X days ago" or "X months from now"
r'(\d+)\s+(minute|hour|day|week|month|year)s?\s+(ago|from now)'

# Matches "last week" or "last month"
r'last\s+(minute|hour|day|week|month|year)'

Quick Note:

Instead of copying these regex into your own code, stick with search_dates()—it’s maintained by the dateparser team, so it’ll stay updated with new formats and bug fixes automatically.


内容的提问来源于stack exchange,提问作者kishore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:55:38