pandas-dev/pandas · error · TypeError
datetime64 type does not support operation
Error message
datetime64 type does not support operation '{how}' What it means
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`.
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.
Example fix
// before
df.groupby('k')['timestamp'].sum() # TypeError
// after
df.groupby('k')['timestamp'].min() # valid reduction
# or, sum of elapsed time:
df['elapsed'] = df['timestamp'] - df['timestamp'].min()
df.groupby('k')['elapsed'].sum() Defensive patterns
Strategy: validation
Validate before calling
import pandas as pd
DISALLOWED_DT_OPS = {'sum', 'prod', 'cumsum', 'cumprod', 'var', 'skew', 'kurt'}
def groupby_dt_safe(df, key, col, how):
if df[col].dtype.kind == 'M' and how in DISALLOWED_DT_OPS:
raise TypeError(f'datetime64 does not support {how}; use min/max/median/mean or subtract a reference first')
return getattr(df.groupby(key)[col], how)() Type guard
import pandas as pd
def is_datetime64_series(s) -> bool:
return getattr(s, 'dtype', None) is not None and s.dtype.kind == 'M' Try / catch
try:
return getattr(df.groupby('k')[date_col], how)()
except TypeError as e:
if 'datetime64 type does not support' in str(e):
return df.groupby('k')[date_col].min()
raise Prevention
- 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.
When it happens
Trigger: df.groupby('key')[date_col].sum(); .prod(), .cumsum(), .cumprod(), .var(), .skew(), .kurt() on a datetime64 column; rolling/expanding windows dispatching the same ops.
Common situations: Generic .sum() across all numeric+datetime columns; migrating legacy aggregation pipelines that used to silently drop datetime columns.
Related errors
- ' ' with datetime64 dtypes is no longer supported. Use (obj…
- mean is not implemented for
- abs(axis) must be less than ndim
- Accumulation not supported for
- cannot add Period to a
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/8998255087089b9b.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/datetimelike.py:1633
# ------------------------------------------------------------------
# GroupBy Methods
def _groupby_op(
self,
*,
how: str,
has_dropped_na: bool,
min_count: int,
ngroups: int,
ids: npt.NDArray[np.intp],
**kwargs,
):
dtype = self.dtype
if dtype.kind == "M":
# Adding/multiplying datetimes is not valid
if how in ["sum", "prod", "cumsum", "cumprod", "var", "skew", "kurt"]:
raise TypeError(f"datetime64 type does not support operation '{how}'")
if how in ["any", "all"]:
# 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(ordinal=0, freq=freq)).{how}() instead."
)
# timedeltas we can add but not multiplyView on GitHub (pinned to 3b7651241d)