Claude Code for python-dateutil: Date and Time Parsing — Claude Skills 360 Blog
Blog / AI / Claude Code for python-dateutil: Date and Time Parsing
AI

Claude Code for python-dateutil: Date and Time Parsing

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

python-dateutil extends Python’s datetime. pip install python-dateutil. Parse: from dateutil import parser. parser.parse("Jan 5, 2024") → datetime. parser.parse("2024-01-05T10:30:00"). parser.parse("next Monday"). parser.parse("5/3/2024", dayfirst=True) → May 3 if dayfirst=True, March 5 if False. parser.parse("01/02/03", yearfirst=True). Fuzzy: parser.parse("Meeting on Jan 5 at 2pm", fuzzy=True) → datetime. parser.parse("...", fuzzy_with_tokens=True) → (datetime, tokens). Timezone: from dateutil.tz import gettz, tzutc, tzlocal. gettz("America/New_York"). gettz("Europe/London"). datetime.now(tzutc()). dt.astimezone(gettz("UTC")). relativedelta: from dateutil.relativedelta import relativedelta. date + relativedelta(months=1) — handles month-end. date + relativedelta(years=1, months=-2, days=10). date + relativedelta(weekday=FR(+1)) — next Friday. relativedelta(dt2, dt1) — diff between dates. relativedelta(months=1).normalized(). rrule: from dateutil.rrule import rrule, DAILY, WEEKLY, MONTHLY, MO, TU, FR. list(rrule(WEEKLY, dtstart=start, until=end, byweekday=[MO,FR])). rrule(MONTHLY, dtstart=start, count=12, bymonthday=-1) — last day of month. rruleset — add and exclude dates. rrulestr("RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR"). Easter: from dateutil.easter import easter; easter(2024) → date. Claude Code generates dateutil parsers, relativedelta arithmetic, and rrule recurrence sequences.

CLAUDE.md for python-dateutil

## python-dateutil Stack
- Version: python-dateutil >= 2.9 | pip install python-dateutil
- Parse: parser.parse("Jan 5 2024") | dayfirst=True | fuzzy=True for embedded dates
- Delta: relativedelta(months=3, days=-1) — calendar-aware, no month-end overflow
- Next weekday: date + relativedelta(weekday=FR(+1)) — next Friday
- Diff: relativedelta(end, start) → .years / .months / .days components
- rrule: rrule(WEEKLY, byweekday=[MO,WE,FR], dtstart=..., until=...) → iterable
- TZ: gettz("America/New_York") | tzutc() | dt.astimezone(gettz("UTC"))

python-dateutil Date and Time Pipeline

# app/dates.py — dateutil parsing, relativedelta arithmetic, and rrule recurrence
from __future__ import annotations

from datetime import date, datetime, timedelta, timezone
from typing import Iterator

from dateutil import parser as dtparser, tz as dttz
from dateutil.easter import easter
from dateutil.relativedelta import FR, MO, SA, SU, TH, TU, WE, relativedelta
from dateutil.rrule import DAILY, MONTHLY, WEEKLY, YEARLY, MO as RMO, FR as RFR, rrule, rruleset, rrulestr


# ─────────────────────────────────────────────────────────────────────────────
# 1. Flexible date string parsing
# ─────────────────────────────────────────────────────────────────────────────

def parse_date(s: str, dayfirst: bool = False, yearfirst: bool = False) -> datetime:
    """
    parser.parse handles ISO 8601, RFC 2822, and many informal formats.
    dayfirst=True → "05/03/2024" parsed as March 5 (European convention).
    dayfirst=False → "05/03/2024" parsed as May 3 (US convention, default).
    """
    return dtparser.parse(s, dayfirst=dayfirst, yearfirst=yearfirst)


def parse_dates_demo() -> None:
    examples = [
        "2024-01-05",
        "Jan 5, 2024",
        "05 January 2024",
        "5th Jan 2024",
        "01/05/2024",
        "2024-01-05T14:30:00",
        "2024-01-05T14:30:00+05:30",
        "Fri, 5 Jan 2024 14:30:00 +0000",
        "January 5th, 2024 at 2:30 PM",
    ]
    for s in examples:
        try:
            parsed = dtparser.parse(s)
            print(f"  {s!r:45}{parsed}")
        except Exception as e:
            print(f"  {s!r:45} → ERROR: {e}")


def extract_date_from_text(text: str) -> tuple[datetime | None, tuple[str, ...]]:
    """
    fuzzy_with_tokens=True extracts a date from free text.
    Returns (datetime, remaining_tokens) — tokens helps identify what was parsed.
    """
    try:
        dt, tokens = dtparser.parse(text, fuzzy_with_tokens=True)
        return dt, tokens
    except dtparser.ParserError:
        return None, ()


# ─────────────────────────────────────────────────────────────────────────────
# 2. relativedelta — calendar-aware arithmetic
# ─────────────────────────────────────────────────────────────────────────────

def add_months(dt: datetime | date, n: int) -> datetime | date:
    """
    Adding months with timedelta(days=30) breaks — Feb 28 + 30 days = Mar 29,
    not April 28. relativedelta(months=1) rolls correctly to the last day.
    """
    return dt + relativedelta(months=n)


def add_years(dt: datetime | date, n: int) -> datetime | date:
    """
    Feb 29 + relativedelta(years=1) → Feb 28 (non-leap year).
    No ValueError from timedelta(days=365) overflow.
    """
    return dt + relativedelta(years=n)


def next_weekday(dt: date, weekday: int) -> date:
    """
    Return the next occurrence of weekday (0=Mon, 6=Sun) after dt.
    relativedelta(weekday=MO(+1)) means "next Monday from this date".
    """
    wd_map = [MO(+1), TU(+1), WE(+1), TH(+1), FR(+1), SA(+1), SU(+1)]
    return dt + relativedelta(weekday=wd_map[weekday])


def last_day_of_month(dt: date) -> date:
    """Return the last day of dt's month."""
    return dt + relativedelta(day=31)   # day=31 clamps to month end


def date_diff_human(d1: date, d2: date) -> dict:
    """
    relativedelta(d2, d1) returns the component-wise difference — useful for
    "you have been a member for 2 years and 3 months" type display.
    """
    delta = relativedelta(d2, d1)
    return {
        "years":  delta.years,
        "months": delta.months,
        "days":   delta.days,
        "total_days": (d2 - d1).days,
    }


def quarter_start(dt: date) -> date:
    """Return the first day of dt's quarter."""
    quarter = (dt.month - 1) // 3
    return date(dt.year, quarter * 3 + 1, 1)


def quarter_end(dt: date) -> date:
    """Return the last day of dt's quarter."""
    next_q_start = quarter_start(dt) + relativedelta(months=3)
    return next_q_start - timedelta(days=1)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Business days
# ─────────────────────────────────────────────────────────────────────────────

def add_business_days(dt: date, n: int, holidays: set[date] | None = None) -> date:
    """Add n business days to dt, skipping weekends and optional holidays."""
    holidays = holidays or set()
    current  = dt
    count    = 0
    direction = 1 if n >= 0 else -1
    target   = abs(n)

    while count < target:
        current = current + timedelta(days=direction)
        if current.weekday() < 5 and current not in holidays:
            count += 1

    return current


def business_days_between(start: date, end: date, holidays: set[date] | None = None) -> int:
    """Count working days between start (exclusive) and end (inclusive)."""
    holidays = holidays or set()
    count    = 0
    current  = start + timedelta(days=1)
    while current <= end:
        if current.weekday() < 5 and current not in holidays:
            count += 1
        current += timedelta(days=1)
    return count


# ─────────────────────────────────────────────────────────────────────────────
# 4. rrule — recurrence sequences
# ─────────────────────────────────────────────────────────────────────────────

def weekly_meetings(
    start: datetime,
    end: datetime,
    days: list = None,
) -> list[datetime]:
    """
    Generate all weekly meeting dates between start and end.
    byweekday=[MO, WE, FR] = Mon, Wed, Fri recurrence.
    """
    return list(rrule(
        WEEKLY,
        dtstart=start,
        until=end,
        byweekday=days or [RMO, RFR],
    ))


def monthly_last_day(year: int) -> list[datetime]:
    """All last-day-of-month dates in a given year."""
    start = datetime(year, 1, 1)
    return list(rrule(
        MONTHLY,
        dtstart=start,
        count=12,
        bymonthday=-1,   # last day
    ))


def parse_rrule(rrule_string: str, dtstart: datetime | None = None) -> list[datetime]:
    """
    Parse an iCalendar RRULE string — useful for calendar integrations.
    Example: "RRULE:FREQ=WEEKLY;BYDAY=MO,WE;COUNT=10"
    """
    return list(rrulestr(rrule_string, dtstart=dtstart or datetime.now(), ignoretz=True))


def payday_schedule(year: int) -> list[date]:
    """
    Semi-monthly paydays: 15th and last day of each month.
    rruleset combines two rrule objects.
    """
    rs = rruleset()
    rs.rrule(rrule(MONTHLY, dtstart=datetime(year, 1, 1),
                   until=datetime(year, 12, 31), bymonthday=15))
    rs.rrule(rrule(MONTHLY, dtstart=datetime(year, 1, 1),
                   until=datetime(year, 12, 31), bymonthday=-1))
    return sorted(set(d.date() for d in rs))


# ─────────────────────────────────────────────────────────────────────────────
# 5. Timezone handling
# ─────────────────────────────────────────────────────────────────────────────

def convert_tz(dt: datetime, to_zone: str) -> datetime:
    """Convert a datetime to a named IANA timezone."""
    target = dttz.gettz(to_zone)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=dttz.tzlocal())
    return dt.astimezone(target)


def make_utc(dt: datetime) -> datetime:
    """Attach UTC timezone to a naive datetime."""
    return dt.replace(tzinfo=dttz.tzutc())


def tz_demo() -> None:
    now_utc = datetime.now(dttz.tzutc())
    for zone in ["America/New_York", "Europe/London", "Asia/Tokyo", "Australia/Sydney"]:
        local = now_utc.astimezone(dttz.gettz(zone))
        print(f"  {zone:30}{local.strftime('%Y-%m-%d %H:%M %Z')}")


# ─────────────────────────────────────────────────────────────────────────────
# 6. Holiday helpers
# ─────────────────────────────────────────────────────────────────────────────

def us_federal_holidays(year: int) -> set[date]:
    """Approximate US federal holiday set using relativedelta."""
    jan1  = date(year, 1, 1)
    return {
        jan1,                                                      # New Year's
        jan1 + relativedelta(month=1, weekday=MO(+3)),             # MLK Day
        jan1 + relativedelta(month=2, weekday=MO(+3)),             # Presidents' Day
        easter(year) - timedelta(days=2),                          # Good Friday (approx)
        date(year, 5, 1) + relativedelta(weekday=MO(+5)),          # Memorial Day (last Mon May)
        date(year, 7, 4),                                          # Independence Day
        date(year, 9, 1) + relativedelta(weekday=MO(+1)),          # Labor Day
        date(year, 11, 1) + relativedelta(weekday=TH(+4)),         # Thanksgiving
        date(year, 12, 25),                                        # Christmas
    }


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

if __name__ == "__main__":
    print("=== Parsing ===")
    parse_dates_demo()

    print("\n=== Fuzzy extraction ===")
    dt, tokens = extract_date_from_text("Please respond by January 15 2024 end of day.")
    print(f"  Extracted: {dt}  Tokens: {tokens}")

    print("\n=== relativedelta ===")
    today = date.today()
    print(f"  +1 month:         {add_months(today, 1)}")
    print(f"  +1 year:          {add_years(today, 1)}")
    print(f"  next Friday:      {next_weekday(today, 4)}")
    print(f"  last of month:    {last_day_of_month(today)}")
    print(f"  quarter start:    {quarter_start(today)}")
    print(f"  quarter end:      {quarter_end(today)}")

    d1 = date(2020, 3, 15)
    d2 = date.today()
    diff = date_diff_human(d1, d2)
    print(f"  diff {d1} → today: {diff['years']}y {diff['months']}m {diff['days']}d")

    print("\n=== Business days ===")
    bd = add_business_days(today, 5)
    wdays = business_days_between(today, today + timedelta(days=14))
    print(f"  +5 business days: {bd}")
    print(f"  workdays in next 2 weeks: {wdays}")

    print("\n=== rrule — weekly meetings ===")
    from datetime import datetime as dt_
    start = dt_(2024, 1, 1)
    end   = dt_(2024, 2, 29)
    meetings = weekly_meetings(start, end)
    print(f"  {len(meetings)} Mon/Fri meetings Jan–Feb 2024")

    print("\n=== Paydays 2024 (first 4) ===")
    pays = payday_schedule(2024)[:4]
    for p in pays:
        print(f"  {p}")

    print("\n=== Timezones ===")
    tz_demo()

For the calendar.monthrange + timedelta(days=30) alternative — adding 30 days to January 31 gives March 2 (skipping February), and manually computing the last day of a month requires calling calendar.monthrange(year, month)[1], while relativedelta(months=1) rolls January 31 to February 28/29 correctly and relativedelta(day=31) returns the last day of the current month without any manual calendar lookup. For the re.search date extraction alternative — writing a regex that matches “Jan 5”, “5th January”, “2024-01-05”, and all common date formats produces hundreds of lines of pattern code, while dateutil.parser.parse(text, fuzzy=True) extracts dates from arbitrary natural language sentences in one call, returning a datetime object with the detected date/time and the non-date tokens as a second value when fuzzy_with_tokens=True. The Claude Skills 360 bundle includes python-dateutil skill sets covering parser.parse with dayfirst/yearfirst, fuzzy and fuzzy_with_tokens for embedded date extraction, relativedelta months/years without overflow, next_weekday with MO/FR weekday constants, last_day_of_month with day=31, date_diff_human with relativedelta(d2, d1), business day arithmetic, rrule WEEKLY/MONTHLY/DAILY with byweekday/bymonthday, rruleset for combined schedules, rrulestr for iCalendar RRULE parsing, and gettz timezone conversion. Start with the free tier to try date parsing and arithmetic 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