{"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":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":1148,"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":1130,"sourceCodeEnd":1166,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/series/series.py#L1130-L1166","documentation":"Series.__truediv__ refuses to divide temporal dtypes (Date, Datetime, Time — but not Duration) because dividing a calendar date by a number has no well-defined meaning. Polars requires casting the temporal value to a numeric type first, making the intent explicit. Duration is exempt because dividing a duration by a number is meaningful.","triggerScenarios":"date_series / 2 or datetime_series / 1_000_000, where the Series dtype is Date, Datetime or Time (is_temporal() is True and the dtype is not Duration). The intent is usually to scale epoch values or convert timestamp units.","commonSituations":"Converting timestamps between units (us -> s) by dividing a Datetime column; porting pandas/numpy code where datetime64 arithmetic silently produced numbers; computing 'days since epoch' directly on a Date column.","solutions":["Cast to integer before dividing: s.cast(pl.Int64) / divisor, then re-cast to a temporal type if needed (e.g. .cast(pl.Datetime('s'))).","For unit conversion use dedicated temporal APIs: s.dt.cast_time_unit('s') for Datetime, or s.dt.epoch(time_unit='s').","For 'days since epoch', compute s.dt.epoch(time_unit='d') rather than dividing the Datetime.","Duration Series divided by numbers is allowed; keep the Duration dtype if scaling a duration is the goal."],"exampleFix":"// before\ns = pl.Series('ts', [datetime(2024, 1, 1)])  # dtype Datetime\ns / 1_000_000  # TypeError: first cast to integer before dividing datelike dtypes\n\n// after\ns.cast(pl.Int64) / 1_000_000  # or s.dt.cast_time_unit('ms')","handlingStrategy":"validation","validationCode":"assert not (s.dtype.is_temporal() and not isinstance(s.dtype, pl.Duration)), \\\n    f'cast {s.dtype} to Int64 (or use .dt accessors) before dividing'","typeGuard":"def dividable(dtype: pl.DataType) -> bool:\n    return not dtype.is_temporal() or isinstance(dtype, pl.Duration)","tryCatchPattern":"try:\n    result = s / other\nexcept TypeError as e:\n    if 'first cast to integer before dividing datelike' in str(e):\n        result = s.cast(pl.Int64) / other\n    else:\n        raise","preventionTips":["Check dtype.is_temporal() before arithmetic on columns whose dtype may be Date/Datetime/Time.","Use .dt accessors (dt.epoch, dt.cast_time_unit, dt.total_*) instead of raw numeric ops on temporal columns.","When converting time units, prefer dt.cast_time_unit over dividing timestamps.","Keep parsing dtypes explicit (pl.Datetime vs pl.Int64) so downstream code knows which operations are legal."],"tags":["python","polars","temporal","division","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"}