pola-rs/polars · error

`time_unit` must be one of

Error message

`time_unit` must be one of {'ms', 'us', 'ns'}, got {time_unit!r}

What it means

Polars raises this ValueError when a time unit string passed to a temporal conversion helper is not one of 'ms', 'us', or 'ns'. The helper `_raise_invalid_time_unit` centralizes validation for datetime/timedelta-to-int and Python-datetime conversions. It prevents silently producing wrongly-scaled integer timestamps.

Solutions

  1. Set time_unit to one of exactly 'ms', 'us', or 'ns'
  2. Normalize aliases before calling, e.g. map 's'/'seconds' to 'ms' if appropriate
  3. If the unit comes from config/user input, validate against the allowed set first

Example fix

// before
pl.Series([1,2]).cast(pl.Datetime(time_unit='seconds'))
// after
pl.Series([1,2]).cast(pl.Datetime(time_unit='ms'))
Defensive patterns

Strategy: validation

Validate before calling

VALID_TIME_UNITS = {"ms", "us", "ns"}
if time_unit not in VALID_TIME_UNITS:
    raise ValueError(f"time_unit must be one of {sorted(VALID_TIME_UNITS)}, got {time_unit!r}")

Type guard

def is_valid_time_unit(u: object) -> TypeGuard[str]:
    return isinstance(u, str) and u in {"ms", "us", "ns"}

Try / catch

try:
    ints = datetime_to_int(dts, time_unit)
except ValueError as e:
    logger.error("bad time_unit: %s", e)
    ints = datetime_to_int(dts, "us")  # polars default

Prevention

When it happens

Trigger: Calling datetime_to_int, timedelta_to_int, to_py_datetime, or to_py_timedelta (or a Polars API like cast/astype on temporal dtypes) with time_unit set to something else, e.g. 's', 'seconds', 'milliseconds', or a non-string value.

Common situations: Translating code from other libraries (pandas/NumPy use 's'), hand-writing a TimeUnit when constructing a Datetime dtype, typo-ing the unit string, or passing a user-config value through unchecked.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/bf558d9290c0a708. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/_utils/convert.py:224

        _raise_invalid_time_unit(time_unit)


def to_py_decimal(prec: int, value: str) -> Decimal:
    """Convert decimal components to a Python Decimal object."""
    return _create_decimal_with_prec(prec)(value)


@lru_cache(None)
def _create_decimal_with_prec(
    precision: int,
) -> Callable[[str], Decimal]:
    # pre-cache contexts so we don't have to spend time on recreating them every time
    return Context(prec=precision).create_decimal


def _raise_invalid_time_unit(time_unit: Any) -> NoReturn:
    msg = f"`time_unit` must be one of {{'ms', 'us', 'ns'}}, got {time_unit!r}"
    raise ValueError(msg)

View on GitHub (pinned to fe841f959e)