pandas-dev/pandas · error · TypeError

timedelta64 type does not support {how} operations

Error message

timedelta64 type does not support {how} operations

What it means

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.

Source

Thrown at pandas/core/arrays/datetimelike.py:1644

                # GH#34479
                raise TypeError(
                    f"'{how}' with datetime64 dtypes is no longer supported. "
                    f"Use (obj != pd.Timestamp(0)).{how}() instead."
                )

        elif isinstance(dtype, PeriodDtype):
            # Adding/multiplying Periods is not valid
            if how in ["sum", "prod", "cumsum", "cumprod", "var", "skew", "kurt"]:
                raise TypeError(f"Period type does not support {how} operations")
            if how in ["any", "all"]:
                # GH#34479
                raise TypeError(
                    f"'{how}' with PeriodDtype is no longer supported. "
                    f"Use (obj != pd.Period(0, freq)).{how}() instead."
                )
        # timedeltas we can add but not multiply
        elif how in ["prod", "cumprod", "skew", "kurt", "var"]:
            raise TypeError(f"timedelta64 type does not support {how} operations")

        # All of the functions implemented here are ordinal, so we can
        #  operate on the tz-naive equivalents
        npvalues = self._ndarray.view("M8[ns]")

        from pandas.core.groupby.ops import WrappedCythonOp

        kind = WrappedCythonOp.get_kind_from_how(how)
        op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na)

        res_values = op._cython_op_ndim_compat(
            npvalues,
            min_count=min_count,
            ngroups=ngroups,
            comp_ids=ids,
            mask=None,
            **kwargs,
        )

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Remove the offending reduction (prod/cumprod/skew/kurt/var) from the call for timedelta columns.
  2. If you need variance/skew, first convert to a numeric unit via .view('int64') or .dt.total_seconds(), then compute the statistic.
  3. When using .agg() over heterogeneous dtypes, pass a dict mapping only valid aggregations per column instead of a flat list.

Example fix

# before
pd.to_timedelta(['1 day','2 days']).prod()

# after (explicitly pick a valid op, or convert to numeric)
seconds = pd.to_timedelta(['1 day','2 days']).dt.total_seconds()
seconds.prod()
Defensive patterns

Strategy: validation

Validate before calling

ALLOWED_TD = {'sum','cumsum','mean','median','min','max','count','rank','quantile'}
requested = {'prod','cumprod','skew','kurt','var'}
if is_timedelta_column(df[c]) and (requested & set(agg_fns)):
    raise ValueError(f'timedeltas do not support {requested & set(agg_fns)}')

Type guard

def is_timedelta_column(s) -> bool:
    return pd.api.types.is_timedelta64_dtype(s)

Try / catch

try:
    grouped.agg(ops)
except TypeError as e:
    if 'timedelta64 type does not support' in str(e):
        ops = [o for o in ops if o not in {'prod','cumprod','skew','kurt','var'}]
        grouped.agg(ops)
    else: raise

Prevention

When it happens

Trigger: 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().

Common situations: 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.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/dc1cdb49dcfaf2b1. Report an issue: GitHub.