pola-rs/polars · error · ValueError

`time_unit` must be one of {valid_units}, got {time_unit!r}

Error message

`time_unit` must be one of {valid_units}, got {time_unit!r}

What it means

Raised by polars.from_epoch when time_unit is not one of the supported epoch units. Supported units are 'ns', 'us', 'ms', 's' and 'd'; anything else (including verbose spellings like 'microseconds' or unsupported units like 'h') reaches the final guard and raises.

Source

Thrown at py-polars/src/polars/functions/lazy.py:2670

        column = F.col(column)
    elif not isinstance(column, (pl.Series, pl.Expr)):
        column = pl.Series(column)

    if time_unit == "d":
        return column.cast(Date)
    if time_unit in (scale := {"s": 1_000_000, "ms": 1_000}):
        if isinstance(column, pl.Expr):
            column = column * F.lit(scale[time_unit], dtype=Int64)
            return column.cast(Datetime("us"))
        if column.dtype.is_integer():
            column = column.cast(Int64)
        return (column * scale[time_unit]).cast(Datetime("us"))
    if time_unit in DTYPE_TEMPORAL_UNITS:
        return column.cast(Datetime(time_unit))  # type: ignore[arg-type]

    valid_units = "'ns', 'us', 'ms', 's', 'd'"
    msg = f"`time_unit` must be one of {valid_units}, got {time_unit!r}"
    raise ValueError(msg)


@deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0")
def rolling_cov(
    a: str | Expr,
    b: str | Expr,
    *,
    window_size: int,
    min_samples: int | None = None,
    ddof: int = 1,
) -> Expr:
    """
    Compute the rolling covariance between two columns/ expressions.

    The window at a given row includes the row itself and the
    `window_size - 1` elements before it.

    .. versionchanged:: 1.21.0

View on GitHub (pinned to df599052da)

Solutions

  1. Use one of the exact short units: 'ns', 'us', 'ms', 's', or 'd'
  2. If the value is in another unit (e.g. minutes or hours), pre-multiply the integer column yourself and then use 's' or 'ms'
  3. Validate configuration-supplied units against the allowlist before calling

Example fix

// before
pl.from_epoch(df['ts'], time_unit='microseconds')
// after
pl.from_epoch(df['ts'], time_unit='us')
Defensive patterns

Strategy: validation

Validate before calling

VALID_EPOCH_UNITS = {'ns', 'us', 'ms', 's', 'd'}
if time_unit not in VALID_EPOCH_UNITS:
    raise ValueError(f'time_unit must be one of {sorted(V_VALID_EPOCH_UNITS) if False else sorted(VALID_EPOCH_UNITS)}')

Type guard

def is_valid_epoch_unit(u: str) -> bool:
    return u in {'ns', 'us', 'ms', 's', 'd'}

Try / catch

try:
    out = pl.from_epoch(col, time_unit=time_unit)
except ValueError as e:
    raise ValueError(f'bad epoch unit in config: {time_unit!r}') from e

Prevention

When it happens

Trigger: pl.from_epoch(df['ts'], time_unit='h'); time_unit='microseconds' or 'milliseconds' instead of 'us'/'ms'; a typo like time_unit='sec'; passing time_unit='M' or 'D' (pandas-style capitalization).

Common situations: Porting pandas or Spark code that uses different unit names; assuming ISO/pandas abbreviations; typos in ETL configuration files that feed time_unit from YAML/JSON.

Related errors


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