{"record":{"id":"739445bd10e3a6a3","repo":"pola-rs/polars","slug":"first-cast-to-integer-before-dividing-datelike-dty","errorCode":null,"errorMessage":"first cast to integer before dividing datelike dtypes","messagePattern":"first cast to integer before dividing datelike dtypes","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":1262,"sourceCode":"                return Array(convert_to_primitive(dtype.inner), shape=dtype.shape)\n            if isinstance(dtype, List):\n                return List(convert_to_primitive(dtype.inner))\n            return leaf_dtype\n\n        return self.cast(convert_to_primitive(self.dtype))\n\n    @overload\n    def __truediv__(self, other: Expr) -> Expr: ...\n\n    @overload\n    def __truediv__(self, other: Any) -> Series: ...\n\n    def __truediv__(self, other: Any) -> Series | Expr:\n        if isinstance(other, pl.Expr):\n            return F.lit(self) / other\n        if self.dtype.is_temporal() and not isinstance(self.dtype, Duration):\n            msg = \"first cast to integer before dividing datelike dtypes\"\n            raise TypeError(msg)\n        if isinstance(other, (int, float)) and (\n            self.dtype.is_decimal() or isinstance(self.dtype, Duration)\n        ):\n            return self.to_frame().select(F.col(self.name) / other).to_series()\n\n        self = (\n            self\n            if (\n                self.dtype.is_float()\n                or self.dtype.is_decimal()\n                or isinstance(self.dtype, (List, Array, Duration))\n                or (\n                    isinstance(other, Series) and isinstance(other.dtype, (List, Array))\n                )\n            )\n            else self._recursive_cast_to_dtype(Float64())\n        )\n","sourceCodeStart":1244,"sourceCodeEnd":1280,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/series/series.py#L1244-L1280","documentation":"Raised by Series.__truediv__ when the left operand is a temporal Series (Date, Datetime, Time) that is not a Duration. Dividing a datelike value by a number has no well-defined unit-aware meaning in Polars, so the operation is refused outright instead of guessing an epoch scale. Duration is exempt because dividing a duration by a scalar (e.g. halving a timespan) is well defined.","triggerScenarios":"Calling `/` on a Series whose dtype satisfies self.dtype.is_temporal() and is not Duration, with a non-Expr right operand: `pl.Series([...]).cast(pl.Date) / 2`, `datetime_series / 7`, `time_series / s2`. The Expr branch (other is pl.Expr) and the Duration/Decimal branches are checked before this raise.","commonSituations":"Developers with pandas/numpy habits try to scale timestamps or normalize dates arithmetically; code that computes fractions of epochs (e.g. 'days since 1970 / 365'); upgrading pipelines where a column silently arrives as Date/Datetime instead of the expected integer epoch.","solutions":["Cast to integer first, then divide: `s.cast(pl.Int64) / n` (use the epoch value in the column's time unit for Datetime).","Use the dt accessors for unit-aware math: `s.dt.total_days() / 7`, `s.dt.epoch('d') / n`, `s.dt.timestamp('ms') / 1_000`.","If you meant duration math (e.g. split a timespan), convert to Duration first: `(end_dt - start_dt) / 2` works because Duration is exempt.","If the column should never be temporal, fix the read/inference: `pl.read_csv(..., schema_overrides={'ts': pl.Int64})` or `.cast(pl.Int64)` right after load."],"exampleFix":"// before\ns = pl.Series([date(2024,1,1), date(2024,1,2)])\ns / 2  # TypeError\n\n// after\ns.cast(pl.Int64) / 2\n# or unit-aware:\ns.dt.epoch(time_unit='d') / 2","handlingStrategy":"type-guard","validationCode":"if s.dtype.is_temporal() and not isinstance(s.dtype, pl.Duration):\n    s = s.cast(pl.Int64)\nresult = s / n","typeGuard":"def is_dividable(s: pl.Series) -> bool:\n    return not (s.dtype.is_temporal() and not isinstance(s.dtype, pl.Duration))","tryCatchPattern":"try:\n    out = s / n\nexcept TypeError as e:\n    if 'datelike' not in str(e):\n        raise\n    out = s.cast(pl.Int64) / n","preventionTips":["Pin dtypes at ingestion with schema_overrides so date-like columns never masquerade as numeric.","In shared math helpers, branch on s.dtype.is_temporal() before applying operators.","Prefer dt accessors (epoch, total_days) for any math touching temporal columns."],"tags":["polars","series","arithmetic","temporal","dtype","truediv"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}