{"record":{"id":"b94ac76c53c97fae","repo":"pola-rs/polars","slug":"first-cast-to-integer-before-applying-modulo-on-da","errorCode":null,"errorMessage":"first cast to integer before applying modulo on datelike dtypes","messagePattern":"first cast to integer before applying modulo on datelike dtypes","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":1226,"sourceCode":"        ):\n            return self.to_frame().select(F.col(self.name) * other).to_series()\n        elif isinstance(other, pl.DataFrame):\n            return other * self\n        else:\n            return self._arithmetic(other, \"mul\", \"mul_<>\")\n\n    @overload\n    def __mod__(self, other: Expr) -> Expr: ...\n\n    @overload\n    def __mod__(self, other: Any) -> Series: ...\n\n    def __mod__(self, other: Any) -> Series | Expr:\n        if isinstance(other, pl.Expr):\n            return F.lit(self).__mod__(other)\n        if self.dtype.is_temporal():\n            msg = \"first cast to integer before applying modulo on datelike dtypes\"\n            raise TypeError(msg)\n        if self.dtype.is_decimal() and isinstance(other, (float, int)):\n            return self.to_frame().select(F.col(self.name) % other).to_series()\n        return self._arithmetic(other, \"rem\", \"rem_<>\")\n\n    def __rmod__(self, other: Any) -> Series:\n        if self.dtype.is_temporal():\n            msg = \"first cast to integer before applying modulo on datelike dtypes\"\n            raise TypeError(msg)\n        return self._arithmetic(other, \"rem\", \"rem_<>_rhs\")\n\n    def __radd__(self, other: Any) -> Series:\n        if isinstance(other, str) or (\n            isinstance(other, (int, float)) and self.dtype.is_decimal()\n        ):\n            return self.to_frame().select(other + F.col(self.name)).to_series()\n        return self._arithmetic(other, \"add\", \"add_<>_rhs\")\n\n    def __rsub__(self, other: Any) -> Series:","sourceCodeStart":1208,"sourceCodeEnd":1244,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/series/series.py#L1208-L1244","documentation":"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.","triggerScenarios":"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.","commonSituations":"Bucketing timestamps by epoch % interval; taking remainders of durations (e.g. leftover seconds); porting numeric pandas idioms that operated on datetime64 views.","solutions":["Cast to integer first: s.cast(pl.Int64) % n, then re-cast to the temporal type if needed.","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.","For bucketing/grouping by time intervals, prefer s.dt.truncate(interval) or group_by_dynamic instead of modulo arithmetic.","__rmod__ has the same guard: cast s to a numeric dtype before computing other % s."],"exampleFix":"// before\ns = pl.Series('d', [date(2024, 1, 1)])  # dtype Date\ns % 7  # TypeError: first cast to integer before applying modulo on datelike dtypes\n\n// after\ns.cast(pl.Int64) % 7  # or use s.dt.weekday() for day-of-week bucketing","handlingStrategy":"validation","validationCode":"assert not s.dtype.is_temporal(), f'cast {s.dtype} to Int64 before applying modulo'","typeGuard":"def mod_safe(dtype: pl.DataType) -> bool:\n    return not dtype.is_temporal()","tryCatchPattern":"try:\n    result = s % n\nexcept TypeError as e:\n    if 'first cast to integer before applying modulo on datelike' in str(e):\n        result = s.cast(pl.Int64) % n\n    else:\n        raise","preventionTips":["Never apply % to Date/Datetime/Time/Duration columns; cast to Int64 or use dt component accessors (dt.hour, dt.weekday, dt.total_seconds).","Use dt.truncate or group_by_dynamic for interval bucketing instead of epoch modulo.","Write helper functions that own the temporal-to-numeric conversion in one place.","Add dtype checks (or schema validation) upstream of numeric operations on timestamp columns."],"tags":["python","polars","temporal","modulo","dtype"],"backgroundTag":"unsupported-operation","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}