calendar.py 4.5 KB
"""统计周期(日历):把「某个周期」解析成具体起止日期。

通用定义:第 M 期 = [M 月偏移 start_month_offset 的 start_day 日, M 月偏移 end_month_offset 的 end_day 日]。
- 自然月:start_day=1, 偏移 0;end_day=last, 偏移 0
- 「上月 26 日到本月 25 日」这类业务月:start_day=26, start_month_offset=-1, end_day=25, end_month_offset=0

问句里的「上个月 / 本月 / 2026年8月 / 近30天」也在这里统一解析。
"""
from __future__ import annotations

import calendar as _cal
import datetime as dt
import re

NATURAL_MONTH = {"start_day": 1, "start_month_offset": 0, "end_day": "last", "end_month_offset": 0}


def _shift(y: int, m: int, off: int) -> tuple[int, int]:
    idx = y * 12 + (m - 1) + off
    return idx // 12, idx % 12 + 1


def _day(y: int, m: int, d) -> dt.date:
    last = _cal.monthrange(y, m)[1]
    if d == "last":
        return dt.date(y, m, last)
    return dt.date(y, m, min(int(d), last))


def period_bounds(spec: dict, year: int, month: int) -> tuple[dt.date, dt.date]:
    spec = {**NATURAL_MONTH, **(spec or {})}
    sy, sm = _shift(year, month, int(spec.get("start_month_offset") or 0))
    ey, em = _shift(year, month, int(spec.get("end_month_offset") or 0))
    return _day(sy, sm, spec.get("start_day", 1)), _day(ey, em, spec.get("end_day", "last"))


def period_of(spec: dict, day: dt.date) -> tuple[int, int]:
    """某一天落在哪一期(返回期的年月)。"""
    for off in (0, 1, -1, 2, -2):
        y, m = _shift(day.year, day.month, off)
        s, e = period_bounds(spec, y, m)
        if s <= day <= e:
            return y, m
    return day.year, day.month


def resolve(spec: dict | None, ref: str = "current", today: dt.date | None = None) -> dict:
    """ref: current / last / prev:N / next / YYYY-MM / YYYY-MM-DD(该日所在期)。"""
    today = today or dt.date.today()
    spec = spec or NATURAL_MONTH
    ref = (ref or "current").strip()
    if re.fullmatch(r"\d{4}-\d{1,2}", ref):
        y, m = (int(x) for x in ref.split("-"))
    elif re.fullmatch(r"\d{4}-\d{1,2}-\d{1,2}", ref):
        y, m = period_of(spec, dt.date(*(int(x) for x in ref.split("-"))))
    else:
        y, m = period_of(spec, today)
        if ref == "last":
            y, m = _shift(y, m, -1)
        elif ref == "next":
            y, m = _shift(y, m, 1)
        elif ref.startswith("prev:"):
            y, m = _shift(y, m, -int(ref.split(":", 1)[1] or 1))
    s, e = period_bounds(spec, y, m)
    return {"period": f"{y:04d}-{m:02d}", "start": s.isoformat(), "end": e.isoformat()}


_CN_NUM = {"一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8,
           "九": 9, "十": 10, "十一": 11, "十二": 12}


def parse_time_phrase(text: str, today: dt.date | None = None) -> dict | None:
    """从问句里识别时间表达,返回 {ref, phrase} 或 {start, end, phrase}。认不出返回 None。"""
    today = today or dt.date.today()
    t = text or ""
    m = re.search(r"(\d{4})\s*年\s*(\d{1,2})\s*月", t)
    if m:
        return {"ref": f"{int(m.group(1)):04d}-{int(m.group(2)):02d}", "phrase": m.group(0)}
    m = re.search(r"(\d{4})-(\d{1,2})(?!-\d)", t)
    if m:
        return {"ref": f"{int(m.group(1)):04d}-{int(m.group(2)):02d}", "phrase": m.group(0)}
    m = re.search(r"(今年|去年)?\s*([一二三四五六七八九十]{1,2}|\d{1,2})\s*月份?", t)
    if m and not re.search(r"(上|下|本|这)个?月", m.group(0)):
        raw = m.group(2)
        mon = _CN_NUM.get(raw) if not raw.isdigit() else int(raw)
        if mon and 1 <= mon <= 12:
            year = today.year - (1 if m.group(1) == "去年" else 0)
            return {"ref": f"{year:04d}-{mon:02d}", "phrase": m.group(0)}
    m = re.search(r"(近|最近|过去)\s*(\d{1,3})\s*天", t)
    if m:
        n = int(m.group(2))
        return {"start": (today - dt.timedelta(days=n)).isoformat(), "end": today.isoformat(),
                "phrase": m.group(0)}
    m = re.search(r"上上个?(月|期)", t)
    if m:
        return {"ref": "prev:2", "phrase": m.group(0)}
    m = re.search(r"(上个?|前一个?)(月|期)", t)
    if m:
        return {"ref": "last", "phrase": m.group(0)}
    m = re.search(r"(本|这个?|当)(月|期)", t)
    if m:
        return {"ref": "current", "phrase": m.group(0)}
    if "昨天" in t:
        d = (today - dt.timedelta(days=1)).isoformat()
        return {"start": d, "end": d, "phrase": "昨天"}
    if "今年" in t:
        return {"start": f"{today.year}-01-01", "end": today.isoformat(), "phrase": "今年"}
    return None