{"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":1633,"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(ordinal=0, freq=freq)).{how}() instead.\"\n                )\n        # timedeltas we can add but not multiply","sourceCodeStart":1615,"sourceCodeEnd":1651,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1615-L1651","documentation":"Raised in _groupby_op (the groupby/reduction dispatcher) when dtype.kind == 'M' (datetime64) and `how` is one of {'sum','prod','cumsum','cumprod','var','skew','kurt'}. Summing or multiplying timestamps is numerically meaningless, so pandas refuses with a per-operation message naming `how`.","triggerScenarios":"df.groupby('key')[date_col].sum(); .prod(), .cumsum(), .cumprod(), .var(), .skew(), .kurt() on a datetime64 column; rolling/expanding windows dispatching the same ops.","commonSituations":"Generic .sum() across all numeric+datetime columns; migrating legacy aggregation pipelines that used to silently drop datetime columns.","solutions":["Use .min()/.max()/.median()/.mean() (or .first()/.last()) for datetime reductions in groupby.","Exclude datetime columns before numeric aggregations: df.select_dtypes(exclude='datetime').","If you need a sum of elapsed time, subtract a reference first: (df[date] - df[date].min()).sum() to aggregate as a Timedelta."],"exampleFix":"// before\ndf.groupby('k')['timestamp'].sum()  # TypeError\n\n// after\ndf.groupby('k')['timestamp'].min()                                   # valid reduction\n# or, sum of elapsed time:\ndf['elapsed'] = df['timestamp'] - df['timestamp'].min()\ndf.groupby('k')['elapsed'].sum()","handlingStrategy":"validation","validationCode":"import pandas as pd\n\nDISALLOWED_DT_OPS = {'sum', 'prod', 'cumsum', 'cumprod', 'var', 'skew', 'kurt'}\n\ndef groupby_dt_safe(df, key, col, how):\n    if df[col].dtype.kind == 'M' and how in DISALLOWED_DT_OPS:\n        raise TypeError(f'datetime64 does not support {how}; use min/max/median/mean or subtract a reference first')\n    return getattr(df.groupby(key)[col], how)()","typeGuard":"import pandas as pd\n\ndef is_datetime64_series(s) -> bool:\n    return getattr(s, 'dtype', None) is not None and s.dtype.kind == 'M'","tryCatchPattern":"try:\n    return getattr(df.groupby('k')[date_col], how)()\nexcept TypeError as e:\n    if 'datetime64 type does not support' in str(e):\n        return df.groupby('k')[date_col].min()\n    raise","preventionTips":["Use min/max/median/mean/first/last for datetime reductions in groupby.","Exclude datetime64 columns before numeric aggregations.","Subtract a reference timestamp to convert to a summable Timedelta."],"tags":["datetime","groupby","reduction","sum","type-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}