pandas-dev/pandas · error · ValueError
Wrong dtype: {data.dtype}
Error message
Wrong dtype: {data.dtype} What it means
Raised by dt64arr_to_periodarr when the input data's dtype is not a datetime64 kind ('M'). The conversion from datetime64 to period ordinals only operates on M-dtyped arrays; integer/object/float inputs are rejected and the caller must convert to datetime64 first.
Source
Thrown at pandas/core/arrays/period.py:1485
Parameters
----------
data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
freq : Optional[Union[str, Tick]]
Must match the `freq` on the `data` if `data` is a DatetimeIndex
or Series.
tz : Optional[tzinfo]
Returns
-------
ordinals : ndarray[int64]
freq : Tick
The frequency extracted from the Series or DatetimeIndex if that's
used.
"""
if not isinstance(data.dtype, np.dtype) or data.dtype.kind != "M":
raise ValueError(f"Wrong dtype: {data.dtype}")
if freq is None:
if isinstance(data, ABCIndex):
data, freq = data._values, data.freq
elif isinstance(data, ABCSeries):
# freq is always None for DatetimeArray inside a Series, so we
# fall back to the inferred freq.
inferred_freq = data._values._inferred_freq_str
if inferred_freq is not None:
warnings.warn(
"Constructing PeriodArray from a Series of datetime64 data "
"will stop inferring the frequency in a future version. "
"Pass `freq` explicitly instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
freq = inferred_freq
data = data._valuesView on GitHub (pinned to 71959b8cb9)
Solutions
- Convert to datetime64 first: data = pd.to_datetime(data).to_numpy().
- Use pd.DatetimeIndex(data) to ensure M dtype before conversion.
- If data is ordinals, use PeriodArray directly instead of dt64arr_to_periodarr.
Example fix
# before import numpy as np dt64arr_to_periodarr(np.array([18262,18263], dtype='int64'), 'D') # after from pandas import to_datetime dt = to_datetime(['2020-01-01','2020-01-02']).to_numpy() dt64arr_to_periodarr(dt, 'D')
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
import pandas as pd
def ensure_datetime64(data):
if not (isinstance(data.dtype, np.dtype) and data.dtype.kind == 'M'):
data = pd.to_datetime(data).to_numpy()
return data Type guard
import numpy as np
def is_datetime64(data) -> bool:
return isinstance(getattr(data, 'dtype', None), np.dtype) and data.dtype.kind == 'M' Try / catch
try:
ordinals, freq = dt64arr_to_periodarr(data, freq)
except ValueError:
ordinals, freq = dt64arr_to_periodarr(pd.to_datetime(data).to_numpy(), freq) Prevention
- Always pd.to_datetime() date-like inputs at load time.
- Check dtype.kind == 'M' before datetime-to-period conversion.
- Do not feed integer epochs into dt64arr_to_periodarr.
When it happens
Trigger: dt64arr_to_periodarr(int_array, freq), period_array(numpy_int_array) routed through the datetime64 path, or passing a DatetimeIndex-without-datetime64-dtype edge case.
Common situations: Loading dates as object strings and forgetting to parse. Passing integer epoch values without converting to datetime64. Custom array subclasses whose dtype kind is not M.
Related errors
- Passing PeriodDtype data is invalid. Use `data.to_timestamp(
- Invalid dtype {dtype} for PeriodArray
- Incorrect dtype
- dtype is not specified and cannot be inferred
- PeriodArray does not allow floating point in construction
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/526ccbc654ded056.
Report an issue: GitHub.