{"record":{"id":"22093928d8f5b8d6","repo":"pandas-dev/pandas","slug":"casting-to-unit-less-dtype-datetime64-is-not-sup","errorCode":null,"errorMessage":"Casting to unit-less dtype 'datetime64' is not supported. Pass e.g. 'datetime64[ns]' instead.","messagePattern":"Casting to unit-less dtype 'datetime64' is not supported\\. Pass e\\.g\\. 'datetime64\\[ns\\]' instead\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimes.py","lineNumber":743,"sourceCode":"            # TODO: preserve freq?\n\n        elif self.tz is not None and lib.is_np_dtype(dtype, \"M\"):\n            # pre-2.0 behavior for DTA/DTI was\n            #  values.tz_convert(\"UTC\").tz_localize(None), which did not match\n            #  the Series behavior\n            raise TypeError(\n                \"Cannot use .astype to convert from timezone-aware dtype to \"\n                \"timezone-naive dtype. Use obj.tz_localize(None) or \"\n                \"obj.tz_convert('UTC').tz_localize(None) instead.\"\n            )\n\n        elif (\n            self.tz is None\n            and lib.is_np_dtype(dtype, \"M\")\n            and dtype != self.dtype\n            and is_unitless(dtype)\n        ):\n            raise TypeError(\n                \"Casting to unit-less dtype 'datetime64' is not supported. \"\n                \"Pass e.g. 'datetime64[ns]' instead.\"\n            )\n\n        elif isinstance(dtype, PeriodDtype):\n            return self.to_period(freq=dtype.freq)\n        return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy)\n\n    # -----------------------------------------------------------------\n    # Rendering Methods\n\n    def _format_native_types(\n        self, *, na_rep: str | float = \"NaT\", date_format=None, **kwargs\n    ) -> npt.NDArray[np.object_]:\n        if date_format is None and self._is_dates_only:\n            # Only dates and no timezone: provide a default format\n            date_format = \"%Y-%m-%d\"\n","sourceCodeStart":725,"sourceCodeEnd":761,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimes.py#L725-L761","documentation":"Raised by DatetimeArray.astype when the array is tz-naive, the target dtype is a numpy datetime64 kind 'M' that differs from the current dtype, and the target is 'unit-less' (i.e. exactly `datetime64` with no `[ns]`/`[s]`/etc. unit). numpy's bare `datetime64` is ambiguous about resolution, so pandas refuses to pick one silently. You must state a concrete unit like `datetime64[ns]`.","triggerScenarios":"Calling `dta.astype('datetime64')`, `dta.astype(np.dtype('M8'))`, or `dta.astype('datetime64')` on a tz-naive DatetimeArray/Index whose dtype already differs from the bare M8 dtype. Distinguished from [312] in that [312] fires at construction/validation time for any input; this fires inside astype specifically.","commonSituations":"User forms a dtype string dynamically (e.g. truncating `'datetime64[ns]'` to `'datetime64'`) or passes an old code path that pre-dates unit-aware datetime64. Confusing numpy's tolerance of unitless datetime64 with pandas' requirement.","solutions":["Pass an explicit unit: `obj.astype('datetime64[ns]')` (or `[s]`, `[ms]`, `[us]`).","If the unit string is built dynamically, ensure the `[unit]` suffix is appended before passing to astype.","If you actually want unit-less numpy semantics, call `.to_numpy()` and handle the resulting ndarray yourself."],"exampleFix":"// before\narr = dta.astype('datetime64')\n\n// after\narr = dta.astype('datetime64[ns]')","handlingStrategy":"validation","validationCode":"import pandas as pd\n\nSUPPORTED_UNITS = {'s', 'ms', 'us', 'ns'}\n\ndef ensure_unit(dtype_str: str) -> str:\n    if dtype_str == 'datetime64' or dtype_str == 'M8':\n        return 'datetime64[ns]'\n    return dtype_str","typeGuard":"import re\ndef is_unitful_datetime_dtype(s: str) -> bool:\n    return bool(re.fullmatch(r'datetime64\\[(s|ms|us|ns)\\]', s))","tryCatchPattern":"try:\n    out = dta.astype(target)\nexcept TypeError as e:\n    if 'unit-less dtype' in str(e):\n        out = dta.astype(target + '[ns]')\n    else:\n        raise","preventionTips":["Never build dtype strings by truncating the `[unit]` suffix.","Validate user-supplied dtype strings before forwarding to astype."],"tags":["datetime","astype","dtype","unit-resolution"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}