{"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/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/datatypes/constructor.py#L102-L138","documentation":"Polars' numpy dtype normaliser (_normalise_numpy_dtype) rejects numpy.datetime64/timedelta64 arrays whose time unit it cannot ingest. Only 'ms', 'us' and 'ns' are supported, plus 'D' for datetime64 only (not timedelta64). Units such as 's', 'm', 'h', 'W', 'M' or 'Y' raise ValueError at conversion time, before any Series is built.","triggerScenarios":"Passing np.ndarray values with dtype datetime64[s|m|h|M|W|Y] or timedelta64[s|m|h|D|M|W|Y] into pl.Series(...), pl.DataFrame(...), or any path that calls numpy_values_and_dtype. Example: pl.Series(np.array(['2024-01-01'], dtype='datetime64[s]')).","commonSituations":"pandas 2.x DataFrames converted via .to_numpy() (pandas now stores datetime64[s]/[ms]); xarray/netCDF time axes; synthetic ranges built with np.arange(..., dtype='timedelta64[h]'); datasets exported with second-level precision.","solutions":["Cast the array to a supported unit before converting: arr.astype('datetime64[us]') (or 'ns'/'ms'); for durations arr.astype('timedelta64[us]')","When coming from pandas, use pl.from_pandas(df), which handles pandas time units itself instead of raw numpy arrays","For timedelta64['D'] (unsupported even though datetime64['D'] is allowed), extract the int day count, multiply by 86_400_000_000, and build a Duration('us') column"],"exampleFix":"# before\ns = pl.Series(np.array(['2024-01-01'], dtype='datetime64[s]'))  # ValueError\n\n# after\ns = pl.Series(np.array(['2024-01-01'], dtype='datetime64[s]').astype('datetime64[us]'))","handlingStrategy":"validation","validationCode":"import numpy as np\n\nSUPPORTED = {'ms', 'us', 'ns'}\n\ndef temporal_unit_ok(arr: np.ndarray) -> bool:\n    if arr.dtype.kind not in 'mM':\n        return True\n    unit, _ = np.datetime_data(arr.dtype)\n    return unit in SUPPORTED or (unit == 'D' and arr.dtype.kind == 'M')\n\nif not temporal_unit_ok(arr):\n    arr = arr.astype('datetime64[us]') if arr.dtype.kind == 'M' else arr.astype('timedelta64[us]')\ns = pl.Series(arr)","typeGuard":"from typing import TypeGuard\nimport numpy as np\n\ndef is_polars_convertible_temporal(arr: np.ndarray) -> TypeGuard[np.ndarray]:\n    if arr.dtype.kind not in 'mM':\n        return True\n    unit, _ = np.datetime_data(arr.dtype)\n    return unit in {'ms', 'us', 'ns'} or (unit == 'D' and arr.dtype.kind == 'M')","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":["Normalise temporal numpy arrays to 'ns' or 'us' at ingestion boundaries","After pandas 2.x .to_numpy(), inspect the dtype unit — pandas may emit datetime64[s]","timedelta64['D'] is not accepted; convert day counts to 'us' manually"],"tags":["numpy","dtype","datetime","timedelta","conversion"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}