{"record":{"id":"8998255087089b9b","repo":"pandas-dev/pandas","slug":"datetime64-type-does-not-support-operation-how","errorCode":null,"errorMessage":"datetime64 type does not support operation '{how}'","messagePattern":"datetime64 type does not support operation '(.+?)'","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1624,"sourceCode":"\n    # ------------------------------------------------------------------\n    # GroupBy Methods\n\n    def _groupby_op(\n        self,\n        *,\n        how: str,\n        has_dropped_na: bool,\n        min_count: int,\n        ngroups: int,\n        ids: npt.NDArray[np.intp],\n        **kwargs,\n    ):\n        dtype = self.dtype\n        if dtype.kind == \"M\":\n            # Adding/multiplying datetimes is not valid\n            if how in [\"sum\", \"prod\", \"cumsum\", \"cumprod\", \"var\", \"skew\", \"kurt\"]:\n                raise TypeError(f\"datetime64 type does not support operation '{how}'\")\n            if how in [\"any\", \"all\"]:\n                # GH#34479\n                raise TypeError(\n                    f\"'{how}' with datetime64 dtypes is no longer supported. \"\n                    f\"Use (obj != pd.Timestamp(0)).{how}() instead.\"\n                )\n\n        elif isinstance(dtype, PeriodDtype):\n            # Adding/multiplying Periods is not valid\n            if how in [\"sum\", \"prod\", \"cumsum\", \"cumprod\", \"var\", \"skew\", \"kurt\"]:\n                raise TypeError(f\"Period type does not support {how} operations\")\n            if how in [\"any\", \"all\"]:\n                # GH#34479\n                raise TypeError(\n                    f\"'{how}' with PeriodDtype is no longer supported. \"\n                    f\"Use (obj != pd.Period(0, freq)).{how}() instead.\"\n                )\n        # timedeltas we can add but not multiply","sourceCodeStart":1606,"sourceCodeEnd":1642,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1606-L1642","documentation":"Raised by _groupby_op when the grouped array is datetime64 and the requested how is one of sum/prod/cumsum/cumprod/var/skew/kurt. Summing or multiplying absolute timestamps is not meaningful, so pandas rejects these reductions on groupby dispatch.","triggerScenarios":"df.groupby(key)[ts_col].sum(), .prod(), .cumsum(), .var(), .skew(), .kurt() on a datetime64 column; reached via the branch at line 1621-1624.","commonSituations":"df.describe() or df.groupby().agg(['sum','mean']) applied blindly to datetime columns; pipelines that aggregate every numeric-looking column including timestamps.","solutions":["Aggregate a numeric column instead, or convert the datetime column: use .min()/.max()/.median()/.count() which are supported.","Compute a duration by subtracting a baseline first: (df['ts'] - df['ts'].min()).groupby(key).sum().","Drop datetime columns before calling generic .sum()/.prod() reductions.","Use .agg() with a function allow-list that excludes sum/prod for datetime dtypes."],"exampleFix":"// before\ndf.groupby('key')['timestamp'].sum()  # TypeError: datetime64 type does not support operation 'sum'\n// after\ndf.groupby('key')['timestamp'].agg(['min','max','count'])","handlingStrategy":"type-guard","validationCode":"from pandas.api.types import is_datetime64_any_dtype\nBAD = {'sum','prod','cumsum','cumprod','var','skew','kurt'}\nif is_datetime64_any_dtype(col.dtype) and how in BAD:\n    how = 'min'  # or skip the column","typeGuard":"def supports_groupby_op(col, how: str) -> bool:\n    from pandas.api.types import is_datetime64_any_dtype\n    BAD = {'sum','prod','cumsum','cumprod','var','skew','kurt'}\n    return not (is_datetime64_any_dtype(col.dtype) and how in BAD)","tryCatchPattern":"try:\n    out = df.groupby('key')['ts'].agg(how)\nexcept TypeError as e:\n    if 'datetime64 type does not support' in str(e):\n        out = df.groupby('key')['ts'].agg(['min','max','count'])\n    else:\n        raise","preventionTips":["Exclude datetime columns from sum/prod/cumsum/var/skew/kurt aggregations.","Use min/max/median/count for datetime reductions.","Subtract a baseline first if a duration sum is needed."],"tags":["groupby","reduction","datetime","unsupported-op"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}