pola-rs/polars · error · TypeError

first cast to integer before applying modulo on datelike…

Error message

first cast to integer before applying modulo on datelike dtypes

What it means

Series.__mod__ (and __rmod__) forbids applying modulo to any temporal dtype, since the remainder of a date/duration division is not defined in polars. The guard runs before the FFI rem dispatch, so all temporal dtypes including Duration are rejected. Users must cast to integers first or use dedicated temporal accessors.

Solutions

  1. Cast to integer first: s.cast(pl.Int64) % n, then re-cast to the temporal type if needed.
  2. Use temporal accessors for remainders of time units: for durations, s.dt.total_seconds() % 60; for datetimes, extract components via s.dt.hour(), s.dt.weekday(), etc.
  3. For bucketing/grouping by time intervals, prefer s.dt.truncate(interval) or group_by_dynamic instead of modulo arithmetic.
  4. __rmod__ has the same guard: cast s to a numeric dtype before computing other % s.

Example fix

// before
s = pl.Series('d', [date(2024, 1, 1)])  # dtype Date
s % 7  # TypeError: first cast to integer before applying modulo on datelike dtypes

// after
s.cast(pl.Int64) % 7  # or use s.dt.weekday() for day-of-week bucketing
Defensive patterns

Strategy: validation

Validate before calling

assert not s.dtype.is_temporal(), f'cast {s.dtype} to Int64 before applying modulo'

Type guard

def mod_safe(dtype: pl.DataType) -> bool:
    return not dtype.is_temporal()

Try / catch

try:
    result = s % n
except TypeError as e:
    if 'first cast to integer before applying modulo on datelike' in str(e):
        result = s.cast(pl.Int64) % n
    else:
        raise

Prevention

When it happens

Trigger: date_series % 7, datetime_series % 2, duration_series % 60 — any use of % (or reversed modulo other % s via __rmod__) where self.dtype.is_temporal() is True.

Common situations: Bucketing timestamps by epoch % interval; taking remainders of durations (e.g. leftover seconds); porting numeric pandas idioms that operated on datetime64 views.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/b94ac76c53c97fae. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/series/series.py:1226

        ):
            return self.to_frame().select(F.col(self.name) * other).to_series()
        elif isinstance(other, pl.DataFrame):
            return other * self
        else:
            return self._arithmetic(other, "mul", "mul_<>")

    @overload
    def __mod__(self, other: Expr) -> Expr: ...

    @overload
    def __mod__(self, other: Any) -> Series: ...

    def __mod__(self, other: Any) -> Series | Expr:
        if isinstance(other, pl.Expr):
            return F.lit(self).__mod__(other)
        if self.dtype.is_temporal():
            msg = "first cast to integer before applying modulo on datelike dtypes"
            raise TypeError(msg)
        if self.dtype.is_decimal() and isinstance(other, (float, int)):
            return self.to_frame().select(F.col(self.name) % other).to_series()
        return self._arithmetic(other, "rem", "rem_<>")

    def __rmod__(self, other: Any) -> Series:
        if self.dtype.is_temporal():
            msg = "first cast to integer before applying modulo on datelike dtypes"
            raise TypeError(msg)
        return self._arithmetic(other, "rem", "rem_<>_rhs")

    def __radd__(self, other: Any) -> Series:
        if isinstance(other, str) or (
            isinstance(other, (int, float)) and self.dtype.is_decimal()
        ):
            return self.to_frame().select(other + F.col(self.name)).to_series()
        return self._arithmetic(other, "add", "add_<>_rhs")

    def __rsub__(self, other: Any) -> Series:

View on GitHub (pinned to fe841f959e)