{"record":{"id":"f441b7d0ad6d994c","repo":"pola-rs/polars","slug":"incorrect-numpy-datetime-resolution-d-datetime","errorCode":null,"errorMessage":"incorrect NumPy datetime resolution\n\n'D' (datetime only), 'ms', 'us', and 'ns' resolutions are supported when converting from numpy.{datetime64,timedelta64}. Please cast to the closest supported unit before converting.","messagePattern":"incorrect NumPy datetime resolution\n\n'D' \\(datetime only\\), 'ms', 'us', and 'ns' resolutions are supported when converting from numpy\\.(.+?)\\. Please cast to the closest supported unit before converting\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/constructor.py","lineNumber":120,"sourceCode":"\n@functools.lru_cache(maxsize=32)\ndef _normalise_numpy_dtype(dtype: Any) -> tuple[Any, Any]:\n    normalised_dtype = (\n        np.dtype(dtype.base.name) if dtype.kind in (\"i\", \"u\", \"f\") else dtype\n    ).type\n    if normalised_dtype in (np.datetime64, np.timedelta64):\n        time_unit = np.datetime_data(dtype)[0]\n        if time_unit in dt.DTYPE_TEMPORAL_UNITS or (\n            time_unit == \"D\" and normalised_dtype == np.datetime64\n        ):\n            return normalised_dtype, np.int64\n        else:\n            msg = (\n                \"incorrect NumPy datetime resolution\"\n                \"\\n\\n'D' (datetime only), 'ms', 'us', and 'ns' resolutions are supported when converting from numpy.{datetime64,timedelta64}.\"\n                \" Please cast to the closest supported unit before converting.\"\n            )\n            raise ValueError(msg)\n    return normalised_dtype, None\n\n\ndef numpy_values_and_dtype(\n    values: np.ndarray[Any, Any],\n) -> tuple[np.ndarray[Any, Any], type]:\n    \"\"\"Return numpy values and their associated dtype, adjusting if required.\"\"\"\n    # Create new dtype object from dtype base name so architecture specific\n    # dtypes (np.longlong np.ulonglong np.intc np.uintc np.longdouble, ...)\n    # get converted to their normalized dtype (np.int*, np.uint*, np.float*).\n    dtype, cast_as = _normalise_numpy_dtype(values.dtype)\n    if cast_as:\n        values = values.astype(cast_as)\n    return values, dtype\n\n\ndef numpy_type_to_constructor(\n    values: np.ndarray[Any, Any], dtype: type[np.dtype[Any]]","sourceCodeStart":102,"sourceCodeEnd":138,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/constructor.py#L102-L138","documentation":"When converting a numpy datetime64/timedelta64 array to a Series, _normalise_numpy_dtype only supports 'D', 'ms', 'us', and 'ns' resolutions. Any other unit ('Y', 'M', 'W', 'h', 'm', 's', or sub-ns like 'fs', 'as') raises this ValueError because polars' internal time representation cannot hold them losslessly.","triggerScenarios":"pl.Series(np.array(['2024-01-01'], dtype='datetime64[s]')) or dtype='datetime64[h]', timedelta64 with 's'/'m'/'h' units, or numpy 2.x attosecond/femtosecond dtypes passed to pl.DataFrame/from_numpy/Series.","commonSituations":"Reading coarse-grained dates stored as datetime64[s] or [h] from other pipelines; pandas-to-polars conversions of second-resolution timestamps; numpy arrays produced with default units like 's'.","solutions":["Cast the numpy array first: arr.astype('datetime64[us]') (or 'ns'/'ms'/'D').","For timedelta: arr.astype('timedelta64[us]').","Convert via Python objects: pl.Series(arr.astype('datetime64[us]')) or pass a list of datetimes."],"exampleFix":"// before\npl.Series(np.array(['2024-01-01'], dtype='datetime64[s]'))\n// after\narr = np.array(['2024-01-01'], dtype='datetime64[s]').astype('datetime64[us]')\npl.Series(arr)","handlingStrategy":"validation","validationCode":"SUPPORTED = {'D', 'ms', 'us', 'ns'}\ndef ensure_supported_dt64(arr: np.ndarray) -> np.ndarray:\n    if arr.dtype.kind in 'mM':\n        unit = arr.dtype.name.split('[')[1].rstrip(']') if '[' in arr.dtype.str else 'us'\n        if unit not in SUPPORTED:\n            arr = arr.astype('datetime64[us]' if arr.dtype.kind == 'M' else 'timedelta64[us]')\n    return arr","typeGuard":null,"tryCatchPattern":"try:\n    s = pl.Series(arr)\nexcept ValueError as e:\n    if \"incorrect NumPy datetime resolution\" in str(e):\n        s = pl.Series(arr.astype('datetime64[us]'))\n    else:\n        raise","preventionTips":["Standardize numpy datetime64 arrays to [us] or [ns] at ingestion boundaries","Check arr.dtype.str before passing datetime64/timedelta64 to polars","Avoid 's', 'h', 'm' unit arrays from upstream sources; cast immediately after load"],"tags":["python","numpy","polars","datetime","dtype"],"backgroundTag":"unsupported-dtype","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}