Add date.toordinal(), date.fromordinal(), datetime.toordinal(), and datetime.fromordinal()

Merged
GA
12d ago
+242-17

Implement proleptic Gregorian day ordinal methods on date and datetime matching CPython 3.14 semantics.

Changes

  • Add Fromordinal and Toordinal variants to StaticStrings.
  • Implement ord_to_year in date.rs to compute Gregorian years for ordinals above 3,652,059, matching CPython's ValueError: year must be in 1..9999, not {year} error format.
  • Implement date_from_ordinal and class_fromordinal on Date, parsing arguments via FromOrdinalArgs with style = parse_tuple to reject keywords (TypeError: fromordinal() takes no keyword arguments) and check arity (TypeError: fromordinal() takes exactly 1 argument (N given)).
  • Expose date.toordinal() and date.fromordinal(), accessible on both class and instance.
  • Implement datetime.toordinal() and datetime.fromordinal(), returning a naive datetime at midnight (00:00:00).
  • Wire class method dispatch in Type::call_attr for Date and DateTime.
  • Update docs/limitations/datetime.md to reflect toordinal and fromordinal() support.
  • Add test coverage in crates/monty/test_cases/datetime__core.py covering boundary ordinals (Day 1 0001-01-01, Day 3,652,059 9999-12-31), leap years, epoch dates, instance invocations, __index__ coercion, ValueError message parity, integer overflow checks (i32 bounds and BigInt), arity checks, and kwarg rejection.

Validation

  • cargo run -p monty-datatest -j 2 -- datetime__ (14/14 tests passed on both Monty and CPython).
  • cargo test -p monty -j 2 --test datetime_format (9/9 tests passed).
  • cargo clippy -p monty -j 2 --all-targets -- -D warnings (passed with zero warnings).
  • cargo +nightly fmt --all (passed).

Summary by cubic

Adds toordinal() and fromordinal() to date and datetime, matching CPython 3.14 semantics, now built on Jiff primitives after the chrono migration.

  • fromordinal(ordinal) constructs a date or a naive datetime at midnight; toordinal() returns the day count since 0001-01-01.
  • Error messages for out-of-range ordinals, kwarg rejection, wrong arity, and __index__ coercion match CPython.
  • Updates the datetime limitations doc and adds boundary, leap-year, and overflow test coverage.