{"record":{"id":"526ccbc654ded056","repo":"pandas-dev/pandas","slug":"wrong-dtype-data-dtype","errorCode":null,"errorMessage":"Wrong dtype: {data.dtype}","messagePattern":"Wrong dtype: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/period.py","lineNumber":1488,"sourceCode":"\n    Parameters\n    ----------\n    data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]\n    freq : Optional[Union[str, Tick]]\n        Must match the `freq` on the `data` if `data` is a DatetimeIndex\n        or Series.\n    tz : Optional[tzinfo]\n\n    Returns\n    -------\n    ordinals : ndarray[int64]\n    freq : Tick\n        The frequency extracted from the Series or DatetimeIndex if that's\n        used.\n\n    \"\"\"\n    if not isinstance(data.dtype, np.dtype) or data.dtype.kind != \"M\":\n        raise ValueError(f\"Wrong dtype: {data.dtype}\")\n\n    if freq is None:\n        if isinstance(data, ABCIndex):\n            data, freq = data._values, data.freq\n        elif isinstance(data, ABCSeries):\n            # freq is always None for DatetimeArray inside a Series, so we\n            #  fall back to the inferred freq.\n            inferred_freq = data._values._inferred_freq_str\n            if inferred_freq is not None:\n                warnings.warn(\n                    \"Constructing PeriodArray from a Series of datetime64 data \"\n                    \"will stop inferring the frequency in a future version. \"\n                    \"Pass `freq` explicitly instead.\",\n                    Pandas4Warning,\n                    stacklevel=find_stack_level(),\n                )\n                freq = inferred_freq\n            data = data._values","sourceCodeStart":1470,"sourceCodeEnd":1506,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L1470-L1506","documentation":"Raised inside dt64arr_to_periodarr when the input array's dtype is not numpy datetime64 (kind != 'M'). The conversion path expects raw datetime64 values to translate into period ordinals; any other dtype (int, float, object, period, etc.) is refused here.","triggerScenarios":"Calling Series.to_period()/DatetimeIndex.to_period() on data that is not datetime64; passing int epoch values or strings to a PeriodArray constructor that goes through the datetime-conversion branch; converting a PeriodIndex back through to_period.","commonSituations":"Forgetting to pd.to_datetime() a column of strings before .to_period(); loading CSV dates as object dtype and calling .to_period('M'); passing epoch ints assuming automatic conversion.","solutions":["Coerce first: pd.to_datetime(series).to_period(freq).","If you have ordinals already, construct PeriodIndex directly with the freq rather than going through this branch.","For numeric epoch data, convert via pd.to_datetime(series, unit='s') first."],"exampleFix":"# before\ndf['col'].to_period('M')  # col is object/str\n# after\npd.to_datetime(df['col']).to_period('M')","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef is_datetime_array(arr) -> bool:\n    return isinstance(arr.dtype, np.dtype) and arr.dtype.kind == 'M'","typeGuard":"import numpy as np\n\ndef to_period_ready(series) -> bool:\n    return hasattr(series, 'dtype') and isinstance(series.dtype, np.dtype) and series.dtype.kind == 'M'","tryCatchPattern":"try:\n    periods = series.to_period(freq)\nexcept ValueError as e:\n    if 'Wrong dtype' in str(e):\n        periods = pd.to_datetime(series).to_period(freq)\n    else:\n        raise","preventionTips":["Always pd.to_datetime() string columns before .to_period().","Check series.dtype.kind == 'M' before converting to period.","When loading CSVs, parse_dates= or dtype= to land datetime64 directly."],"tags":["pandas","period","dtype","datetime"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}