Claude Code for dateparser: Natural Language Date Parsing — Claude Skills 360 Blog
Blog / AI / Claude Code for dateparser: Natural Language Date Parsing
AI

Claude Code for dateparser: Natural Language Date Parsing

Published: February 24, 2028
Read time: 5 min read
By: Claude Skills 360

dateparser parses natural language date strings in many languages. pip install dateparser. Basic: import dateparser; dateparser.parse("yesterday") → datetime. dateparser.parse("next Friday"). dateparser.parse("3 days ago"). dateparser.parse("Jan 5 2024"). dateparser.parse("5 janvier 2024") — French. dateparser.parse("今天") — Chinese “today”. Settings: dateparser.parse("05/03/24", settings={"PREFER_DAY_OF_MONTH":"first","PREFER_DATES_FROM":"future"}). PREFER_DATES_FROM: “past” “future” “current_period”. DATE_ORDER: “DMY” “MDY” “YMD”. RETURN_TIME_AS_PERIOD: “time” returns (start, end) tuple. TIMEZONE: settings={"TIMEZONE":"US/Eastern"} — localize to tz. RETURN_AS_TIMEZONE_AWARE: settings={"RETURN_AS_TIMEZONE_AWARE":True}. RELATIVE_BASE: settings={"RELATIVE_BASE":datetime(2024,1,1)} — anchor for “yesterday”/“tomorrow”. STRICT_PARSING: settings={"STRICT_PARSING":True} — reject ambiguous. PREFER_LOCALE_DATE_ORDER: use system locale for day/month order. Search: from dateparser.search import search_dates. search_dates("Meeting on Jan 5 at 2pm and follow-up March 10") → list of (string, datetime). Languages: settings={"LANGUAGES":["de","fr","es"]} — restrict parsing to specific languages. Speed: from dateparser.search import search_dates. Pandas: df["date"] = df["date_str"].map(dateparser.parse). Claude Code generates dateparser extractors, pandas date parsers, and multilingual date normalizers.

CLAUDE.md for dateparser

## dateparser Stack
- Version: dateparser >= 1.2 | pip install dateparser
- Parse: dateparser.parse("3 days ago") | dateparser.parse("next Monday") | parse("Jan 5")
- Settings: {"PREFER_DATES_FROM":"future"} | {"DATE_ORDER":"DMY"} | {"TIMEZONE":"UTC"}
- Timezone: {"RETURN_AS_TIMEZONE_AWARE":True, "TIMEZONE":"US/Eastern"}
- Relative base: {"RELATIVE_BASE":datetime(2024,1,1)} — anchor "yesterday"/"next week"
- Search: search_dates(text) → list of (string, datetime) from free text
- Strict: {"STRICT_PARSING":True} — raise/return None for ambiguous strings

dateparser Natural Language Date Pipeline

# app/date_parse.py — dateparser natural language date parsing and extraction
from __future__ import annotations

import re
from datetime import datetime, timezone
from typing import Any

import dateparser
from dateparser.search import search_dates


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic parsing helpers
# ─────────────────────────────────────────────────────────────────────────────

def parse_date(
    text: str,
    prefer: str = "past",
    tz: str | None = None,
    date_order: str = "MDY",
    base: datetime | None = None,
    strict: bool = False,
) -> datetime | None:
    """
    Parse a natural language date string.
    prefer="past"/"future"/"current_period" — which direction for ambiguous relative dates.
    tz: IANA timezone string ("America/New_York") for timezone-aware output.
    date_order: "MDY" (US), "DMY" (European), "YMD" (ISO).
    base: anchor for relative dates like "yesterday" (defaults to now).
    strict=True: return None for ambiguous strings instead of guessing.
    """
    settings: dict[str, Any] = {
        "PREFER_DATES_FROM":         prefer,
        "DATE_ORDER":                 date_order,
        "RETURN_AS_TIMEZONE_AWARE":  bool(tz),
        "STRICT_PARSING":             strict,
    }
    if tz:
        settings["TIMEZONE"] = tz
    if base:
        settings["RELATIVE_BASE"] = base

    return dateparser.parse(text, settings=settings)


def parse_date_utc(text: str) -> datetime | None:
    """Parse a date string and return a UTC-aware datetime."""
    return parse_date(text, tz="UTC", prefer="past")


def parse_date_strict(text: str, date_order: str = "MDY") -> datetime | None:
    """
    Strict parsing — returns None for ambiguous strings that could be multiple dates.
    Use when you need to reject uncertain parses.
    """
    return dateparser.parse(text, settings={
        "STRICT_PARSING": True,
        "DATE_ORDER": date_order,
    })


# ─────────────────────────────────────────────────────────────────────────────
# 2. Multilingual parsing
# ─────────────────────────────────────────────────────────────────────────────

def parse_multilingual(text: str, languages: list[str] | None = None) -> datetime | None:
    """
    Parse a date in any of the specified languages.
    dateparser detects language automatically if languages=None.
    Restrict to a list for better accuracy when you know the input language.

    Examples:
    "5 janvier 2024"        → French
    "5. Januar 2024"        → German
    "5 de enero de 2024"    → Spanish
    "5 января 2024"         → Russian
    "2024年1月5日"            → Japanese
    """
    settings: dict[str, Any] = {}
    if languages:
        settings["LANGUAGES"] = languages
    return dateparser.parse(text, settings=settings)


def parse_eu_date(text: str) -> datetime | None:
    """Parse a European date string (day-first order: 5/3/2024 = March 5th)."""
    return dateparser.parse(text, settings={"DATE_ORDER": "DMY"})


def parse_iso_date(text: str) -> datetime | None:
    """Parse an ISO/Asian date string (year-first: 2024/1/5)."""
    return dateparser.parse(text, settings={"DATE_ORDER": "YMD"})


# ─────────────────────────────────────────────────────────────────────────────
# 3. Relative date parsing with custom base
# ─────────────────────────────────────────────────────────────────────────────

def parse_relative(text: str, base: datetime) -> datetime | None:
    """
    Parse a relative date expression anchored to a specific base datetime.
    Essential for reproducible tests and for processing historical documents
    where "next week" should be relative to the document date, not today.
    """
    return dateparser.parse(text, settings={
        "RELATIVE_BASE":          base,
        "PREFER_DATES_FROM":      "future",
        "RETURN_AS_TIMEZONE_AWARE": False,
    })


def relative_dates_from_base(
    expressions: list[str],
    base: datetime,
) -> list[datetime | None]:
    """Parse a list of relative date expressions from the same base."""
    return [parse_relative(expr, base) for expr in expressions]


# ─────────────────────────────────────────────────────────────────────────────
# 4. Search — extract multiple dates from free text
# ─────────────────────────────────────────────────────────────────────────────

def find_dates_in_text(
    text: str,
    languages: list[str] | None = None,
    add_detected_language: bool = False,
) -> list[dict[str, Any]]:
    """
    Extract all date references from free text.
    search_dates() returns [(matched_string, datetime), ...].
    Useful for parsing meeting notes, emails, and documents.
    """
    settings: dict[str, Any] = {}
    if languages:
        settings["LANGUAGES"] = languages

    results = search_dates(
        text,
        settings=settings,
        add_detected_language=add_detected_language,
    ) or []

    if add_detected_language:
        return [
            {"text": r[0], "date": r[1], "language": r[2]}
            for r in results
        ]
    return [{"text": r[0], "date": r[1]} for r in results]


def extract_first_date(text: str) -> datetime | None:
    """Extract the first date found in a block of text."""
    found = find_dates_in_text(text)
    return found[0]["date"] if found else None


def extract_date_range(text: str) -> tuple[datetime | None, datetime | None]:
    """
    Extract the first two dates from text as (start, end).
    Useful for "between Jan 5 and Jan 10" or "from Monday to Friday".
    """
    found = find_dates_in_text(text)
    dates = [f["date"] for f in found if f["date"]]
    start = dates[0] if len(dates) > 0 else None
    end   = dates[1] if len(dates) > 1 else None
    return start, end


# ─────────────────────────────────────────────────────────────────────────────
# 5. Batch / pandas integration
# ─────────────────────────────────────────────────────────────────────────────

def parse_series(
    values: list[str | None],
    prefer: str = "past",
    date_order: str = "MDY",
    tz: str | None = None,
) -> list[datetime | None]:
    """
    Parse a list of date strings.
    For pandas: df["parsed"] = parse_series(df["date_str"].tolist())
    """
    settings: dict[str, Any] = {
        "PREFER_DATES_FROM": prefer,
        "DATE_ORDER":         date_order,
    }
    if tz:
        settings["TIMEZONE"] = tz
        settings["RETURN_AS_TIMEZONE_AWARE"] = True

    results = []
    for v in values:
        if not v or not str(v).strip():
            results.append(None)
            continue
        try:
            results.append(dateparser.parse(str(v), settings=settings))
        except Exception:
            results.append(None)
    return results


def normalize_dates_dataframe(df, column: str, new_column: str | None = None, **kwargs):
    """
    Parse a pandas DataFrame column of mixed date strings into datetime.
    new_column=None overwrites the source column.
    """
    import pandas as pd
    out_col = new_column or column
    df[out_col] = parse_series(df[column].tolist(), **kwargs)
    return df


# ─────────────────────────────────────────────────────────────────────────────
# 6. Validation and normalization
# ─────────────────────────────────────────────────────────────────────────────

def is_valid_date_string(text: str) -> bool:
    """Return True if the string can be parsed as a date."""
    return parse_date_strict(text) is not None


def normalize_to_iso(text: str, prefer: str = "past") -> str | None:
    """Parse a date string and return ISO 8601 format (YYYY-MM-DD) or None."""
    dt = parse_date(text, prefer=prefer)
    return dt.strftime("%Y-%m-%d") if dt else None


def normalize_to_timestamp(text: str) -> float | None:
    """Parse a date string and return a Unix timestamp or None."""
    dt = parse_date_utc(text)
    return dt.timestamp() if dt else None


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== Natural language parsing ===")
    expressions = [
        "yesterday",
        "next Monday",
        "3 days ago",
        "in 2 weeks",
        "last month",
        "January 5, 2024",
        "Jan 5 at 2:30pm",
        "2024-01-05",
        "5/3/2024",
        "first day of next month",
    ]
    for expr in expressions:
        dt = parse_date(expr)
        print(f"  {expr!r:35}{dt}")

    print("\n=== Multilingual ===")
    ml_samples = [
        ("5 janvier 2024",     ["fr"]),
        ("5. Januar 2024",     ["de"]),
        ("5 enero 2024",       ["es"]),
        ("5 января 2024",      ["ru"]),
    ]
    for text, langs in ml_samples:
        dt = parse_multilingual(text, langs)
        print(f"  {text!r:30}{dt}")

    print("\n=== Relative base ===")
    base = datetime(2024, 3, 15)
    relative_exprs = ["yesterday", "next week", "in 3 days", "last Friday"]
    for expr in relative_exprs:
        dt = parse_relative(expr, base)
        print(f"  Base 2024-03-15 + {expr!r:15}{dt}")

    print("\n=== Search in text ===")
    email = """
    Hi team — please note the quarterly review is on March 15, 2024.
    Expenses are due by end of day February 28.
    The next team sync is every Monday at 10am starting January 8.
    """
    found = find_dates_in_text(email)
    for f in found:
        print(f"  {f['text']!r:30}{f['date']}")

    print("\n=== ISO normalization ===")
    for s in ["yesterday", "Jan 5 2024", "last Tuesday", "invalid text"]:
        iso = normalize_to_iso(s)
        print(f"  {s!r:20}{iso!r}")

    print("\n=== Batch parsing ===")
    dates = ["Jan 5 2024", "yesterday", "next Friday", None, "invalid", "2024-03-15"]
    parsed = parse_series(dates)
    for raw, dt in zip(dates, parsed):
        print(f"  {str(raw):20}{dt}")

For the python-dateutil alternative — dateutil.parser.parse() handles ISO 8601 and many standard formats with ~95% coverage, and its fuzzy_with_tokens=True mode extracts dates from text; dateparser adds multilingual support ("5 janvier 2024", "5. Januar 2024", "5 de enero 2024" all produce the same datetime), relative expression parsing (“next Monday”, “3 days ago”, “last quarter”), search_dates() for extracting multiple dates from a paragraph, and the RELATIVE_BASE setting that anchors “yesterday” to a specific datetime instead of now — necessary for reproducible test fixtures and historical document processing. For the spaCy NER alternative — spaCy’s Named Entity Recognition can tag DATE and TIME entities in text, but it returns the raw matched string, not a datetime object; dateparser’s search_dates() returns (string, datetime) pairs without requiring a spaCy model download or pipeline setup, making it the right choice when the goal is datetime objects, not token classification. The Claude Skills 360 bundle includes dateparser skill sets covering dateparser.parse() with PREFER_DATES_FROM/DATE_ORDER/TIMEZONE settings, parse_date_utc() and parse_date_strict(), parse_multilingual() with LANGUAGES list, parse_eu_date() DMY and parse_iso_date() YMD order, parse_relative() with RELATIVE_BASE anchor, search_dates() text extraction, find_dates_in_text() structured output, extract_date_range() first/second date pair, parse_series() for batch list processing, normalize_dates_dataframe() pandas integration, normalize_to_iso() for YYYY-MM-DD output, and is_valid_date_string() validator. Start with the free tier to try natural language date parsing code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free