pola-rs/polars · error · ValueError

incorrect NumPy datetime resolution 'D' (datetime only), 'm

Error message

incorrect NumPy datetime resolution

'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.

What it means

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.

Source

Thrown at py-polars/src/polars/datatypes/constructor.py:120

@functools.lru_cache(maxsize=32)
def _normalise_numpy_dtype(dtype: Any) -> tuple[Any, Any]:
    normalised_dtype = (
        np.dtype(dtype.base.name) if dtype.kind in ("i", "u", "f") else dtype
    ).type
    if normalised_dtype in (np.datetime64, np.timedelta64):
        time_unit = np.datetime_data(dtype)[0]
        if time_unit in dt.DTYPE_TEMPORAL_UNITS or (
            time_unit == "D" and normalised_dtype == np.datetime64
        ):
            return normalised_dtype, np.int64
        else:
            msg = (
                "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."
            )
            raise ValueError(msg)
    return normalised_dtype, None


def numpy_values_and_dtype(
    values: np.ndarray[Any, Any],
) -> tuple[np.ndarray[Any, Any], type]:
    """Return numpy values and their associated dtype, adjusting if required."""
    # Create new dtype object from dtype base name so architecture specific
    # dtypes (np.longlong np.ulonglong np.intc np.uintc np.longdouble, ...)
    # get converted to their normalized dtype (np.int*, np.uint*, np.float*).
    dtype, cast_as = _normalise_numpy_dtype(values.dtype)
    if cast_as:
        values = values.astype(cast_as)
    return values, dtype


def numpy_type_to_constructor(
    values: np.ndarray[Any, Any], dtype: type[np.dtype[Any]]

View on GitHub (pinned to df599052da)

Solutions

  1. Cast the array to a supported unit before converting: arr.astype('datetime64[us]') (or 'ns'/'ms'); for durations arr.astype('timedelta64[us]')
  2. When coming from pandas, use pl.from_pandas(df), which handles pandas time units itself instead of raw numpy arrays
  3. 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

Example fix

# before
s = pl.Series(np.array(['2024-01-01'], dtype='datetime64[s]'))  # ValueError

# after
s = pl.Series(np.array(['2024-01-01'], dtype='datetime64[s]').astype('datetime64[us]'))
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

SUPPORTED = {'ms', 'us', 'ns'}

def temporal_unit_ok(arr: np.ndarray) -> bool:
    if arr.dtype.kind not in 'mM':
        return True
    unit, _ = np.datetime_data(arr.dtype)
    return unit in SUPPORTED or (unit == 'D' and arr.dtype.kind == 'M')

if not temporal_unit_ok(arr):
    arr = arr.astype('datetime64[us]') if arr.dtype.kind == 'M' else arr.astype('timedelta64[us]')
s = pl.Series(arr)

Type guard

from typing import TypeGuard
import numpy as np

def is_polars_convertible_temporal(arr: np.ndarray) -> TypeGuard[np.ndarray]:
    if arr.dtype.kind not in 'mM':
        return True
    unit, _ = np.datetime_data(arr.dtype)
    return unit in {'ms', 'us', 'ns'} or (unit == 'D' and arr.dtype.kind == 'M')

Try / catch

try:
    s = pl.Series(arr)
except ValueError as e:
    if 'incorrect NumPy datetime resolution' in str(e):
        s = pl.Series(arr.astype('datetime64[us]'))
    else:
        raise

Prevention

When it happens

Trigger: 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]')).

Common situations: 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.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/f441b7d0ad6d994c. Report an issue: GitHub.