{"record":{"id":"dc1cdb49dcfaf2b1","repo":"pandas-dev/pandas","slug":"timedelta64-type-does-not-support-how-operations","errorCode":null,"errorMessage":"timedelta64 type does not support {how} operations","messagePattern":"timedelta64 type does not support (.+?) operations","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1644,"sourceCode":"                # 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\n        elif how in [\"prod\", \"cumprod\", \"skew\", \"kurt\", \"var\"]:\n            raise TypeError(f\"timedelta64 type does not support {how} operations\")\n\n        # All of the functions implemented here are ordinal, so we can\n        #  operate on the tz-naive equivalents\n        npvalues = self._ndarray.view(\"M8[ns]\")\n\n        from pandas.core.groupby.ops import WrappedCythonOp\n\n        kind = WrappedCythonOp.get_kind_from_how(how)\n        op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na)\n\n        res_values = op._cython_op_ndim_compat(\n            npvalues,\n            min_count=min_count,\n            ngroups=ngroups,\n            comp_ids=ids,\n            mask=None,\n            **kwargs,\n        )","sourceCodeStart":1626,"sourceCodeEnd":1662,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1626-L1662","documentation":"Raised by DatetimeLikeArrayMixin._groupby_reduce when a reduction operation that is mathematically meaningless for timedeltas is requested. The {how} placeholder is one of 'prod', 'cumprod', 'skew', 'kurt', 'var' — operations involving multiplication or dimensionful variance that have no defined result for a duration. Timedeltas support addition/subtraction (sum, cumsum) but not products or moments that assume a real-valued domain.","triggerScenarios":"Calling .prod(), .cumprod(), .skew(), .kurt(), or .var() (or groupby(...).prod()/var()/skew()/kurt()) on a TimedeltaArray, TimedeltaIndex, or a Series of timedelta64 dtype. For example: pd.to_timedelta(['1 day','2 days']).prod() or df.groupby('g')['dur'].var().","commonSituations":"Aggregating a duration/logged-time column (e.g. response latencies, session lengths) with a generic .agg(['sum','prod','var']) call copied from numeric code. Descriptive-statistics templates that run every reduction on every column. Migrating code that treated timedeltas as integers pre-2.0.","solutions":["Remove the offending reduction (prod/cumprod/skew/kurt/var) from the call for timedelta columns.","If you need variance/skew, first convert to a numeric unit via .view('int64') or .dt.total_seconds(), then compute the statistic.","When using .agg() over heterogeneous dtypes, pass a dict mapping only valid aggregations per column instead of a flat list."],"exampleFix":"# before\npd.to_timedelta(['1 day','2 days']).prod()\n\n# after (explicitly pick a valid op, or convert to numeric)\nseconds = pd.to_timedelta(['1 day','2 days']).dt.total_seconds()\nseconds.prod()","handlingStrategy":"validation","validationCode":"ALLOWED_TD = {'sum','cumsum','mean','median','min','max','count','rank','quantile'}\nrequested = {'prod','cumprod','skew','kurt','var'}\nif is_timedelta_column(df[c]) and (requested & set(agg_fns)):\n    raise ValueError(f'timedeltas do not support {requested & set(agg_fns)}')","typeGuard":"def is_timedelta_column(s) -> bool:\n    return pd.api.types.is_timedelta64_dtype(s)","tryCatchPattern":"try:\n    grouped.agg(ops)\nexcept TypeError as e:\n    if 'timedelta64 type does not support' in str(e):\n        ops = [o for o in ops if o not in {'prod','cumprod','skew','kurt','var'}]\n        grouped.agg(ops)\n    else: raise","preventionTips":["Build per-column aggregation dicts keyed by dtype instead of one global list.","Unit-test aggregations against a dataframe containing a timedelta column."],"tags":["timedelta","reduction","groupby","type-error"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}