Skip to content

dates

Explicit calendar date extraction from English text.

DateMention dataclass

DateMention(text: str, start: int, end: int, resolution: int, month: int, day: int, year: int)

A calendar date with a source span and known date components.

Attributes:

Name Type Description
text str

Matched date text.

start int

Zero-based character offset.

end int

Exclusive end offset.

resolution int

1 for year, 2 for month/year, 3 for full date, 4 for month/day.

month int

Month number, or zero when absent.

day int

Day number, or zero when absent.

year int

Year, or zero when absent.

DateIssue dataclass

DateIssue(text: str, start: int, reason: str)

An ambiguous or invalid date candidate with its text, offset, and reason.

DateResult dataclass

DateResult(text: str, mentions: tuple[DateMention, ...], issues: tuple[DateIssue, ...] = ())

Date mentions and rejected candidates for an input body.

Attributes:

Name Type Description
text str

Analyzed body.

mentions tuple[DateMention, ...]

Accepted dates in source order.

issues tuple[DateIssue, ...]

Ambiguous or invalid candidates in source order.

to_gkg

to_gkg()

Serialize the enhanced dates field, or an empty string for no matches.

Source code in src/gdelt_regkg/fields/dates.py
def to_gkg(self):
    """Serialize the enhanced dates field, or an empty string for no matches."""
    return ";".join(m.to_gkg() for m in self.mentions)

analyze_dates

analyze_dates(text: str, *, numeric_order: NumericDateOrder | None = None) -> DateResult

Extract calendar dates and years from 1500 through 2199.

Missing components stay zero. Ambiguous numeric dates are reported as issues unless numeric_order resolves them.

Parameters:

Name Type Description Default
text str

Prepared English body.

required
numeric_order NumericDateOrder | None

mdy, dmy, or None to retain ambiguous dates as issues.

None

Returns:

Type Description
DateResult

Accepted date mentions and diagnostics with source character offsets.

Raises:

Type Description
TypeError

If text is not a string.

ValueError

If numeric_order is unsupported.

Source code in src/gdelt_regkg/fields/dates.py
def analyze_dates(text: str, *, numeric_order: NumericDateOrder | None = None) -> DateResult:
    """Extract calendar dates and years from 1500 through 2199.

    Missing components stay zero. Ambiguous numeric dates are reported as issues
    unless `numeric_order` resolves them.

    Args:
        text: Prepared English body.
        numeric_order: `mdy`, `dmy`, or `None` to retain ambiguous dates as issues.

    Returns:
        Accepted date mentions and diagnostics with source character offsets.

    Raises:
        TypeError: If `text` is not a string.
        ValueError: If `numeric_order` is unsupported.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    if numeric_order not in {None, "mdy", "dmy"}:
        raise ValueError("numeric_order must be mdy, dmy, or None")
    occupied: list[tuple[int, int]] = []
    mentions, issues = [], []
    for kind, pattern in _PATTERNS:
        for match in pattern.finditer(text):
            start, end = match.span()
            if any(start < b and a < end for a, b in occupied):
                continue
            # Standalone years next to quantities are not calendar references.
            if kind == "year" and re.match(
                r"\s*(?:percent|people|residents|houses|trucks|soldiers|dollars|euros|pounds|million|billion|kg|km)\b",
                text[end:],
                re.I,
            ):
                continue
            occupied.append((start, end))
            groups = match.groupdict()
            year = int(groups.get("y") or 0)
            day = int(re.sub(r"\D", "", groups.get("d") or "0"))
            month = groups.get("m") or "0"
            month = _MONTHS[month.lower().rstrip(".")] if kind in {"named", "month"} else int(month)
            if kind == "numeric":
                a, b = int(groups["a"]), int(groups["b"])
                if numeric_order is None and a <= 12 and b <= 12 and a != b:
                    issues.append(DateIssue(match[0], start, "ambiguous-numeric-date"))
                    continue
                month, day = (
                    (b, a)
                    if numeric_order == "dmy" or (numeric_order is None and a > 12)
                    else (a, b)
                )
            resolution = 1 if kind == "year" else 2 if kind == "month" else 3 if year else 4
            try:
                mentions.append(DateMention(match[0], start, end, resolution, month, day, year))
            except ValueError:
                issues.append(DateIssue(match[0], start, "invalid-calendar-date"))
    return DateResult(
        text,
        tuple(sorted(mentions, key=lambda m: m.start)),
        tuple(sorted(issues, key=lambda m: m.start)),
    )