{"record":{"id":"069042b65910bd47","repo":"pola-rs/polars","slug":"time-unit-must-be-one-of-ns-us-ms-s","errorCode":null,"errorMessage":"`time_unit` must be one of {'ns', 'us', 'ms', 's', 'd'}, got {time_unit!r}","messagePattern":"`time_unit` must be one of (.+?), got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/expr/datetime.py","lineNumber":1853,"sourceCode":"        ┌────────────┬─────────────────┬───────────┐\n        │ date       ┆ epoch_ns        ┆ epoch_s   │\n        │ ---        ┆ ---             ┆ ---       │\n        │ date       ┆ i64             ┆ i64       │\n        ╞════════════╪═════════════════╪═══════════╡\n        │ 2001-01-01 ┆ 978307200000000 ┆ 978307200 │\n        │ 2001-01-02 ┆ 978393600000000 ┆ 978393600 │\n        │ 2001-01-03 ┆ 978480000000000 ┆ 978480000 │\n        └────────────┴─────────────────┴───────────┘\n        \"\"\"\n        if time_unit in DTYPE_TEMPORAL_UNITS:\n            return self.timestamp(time_unit)  # type: ignore[arg-type]\n        elif time_unit == \"s\":\n            return self.timestamp(\"ms\") // F.lit(1000, Int64)\n        elif time_unit == \"d\":\n            return wrap_expr(self._pyexpr).cast(Date).cast(Int32)\n        else:\n            msg = f\"`time_unit` must be one of {{'ns', 'us', 'ms', 's', 'd'}}, got {time_unit!r}\"\n            raise ValueError(msg)\n\n    def timestamp(self, time_unit: TimeUnit = \"us\") -> Expr:\n        \"\"\"\n        Return a timestamp in the given time unit.\n\n        .. engine-support:: in-memory, streaming, distributed\n\n        Parameters\n        ----------\n        time_unit : {'ns', 'us', 'ms'}\n            Time unit.\n\n        Examples\n        --------\n        >>> from datetime import date\n        >>> df = (\n        ...     pl.date_range(date(2001, 1, 1), date(2001, 1, 3), eager=True)\n        ...     .alias(\"date\")","sourceCodeStart":1835,"sourceCodeEnd":1871,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/expr/datetime.py#L1835-L1871","documentation":"Expr.dt.epoch extracts a timestamp as an integer and accepts only 'ns', 'us', 'ms', 's', and 'd'. 's' is computed as timestamp('ms') // 1000 and 'd' casts via Date to Int32; every other value raises ValueError. There is no case folding or plural handling.","triggerScenarios":"pl.col('ts').dt.epoch('sec'), .dt.epoch('seconds'), .dt.epoch('minutes'), or .dt.epoch('h') — anything outside {'ns','us','ms','s','d'}.","commonSituations":"Porting pandas/numpy unit conventions ('s' vs 'seconds'); unit strings sourced from user input or config and passed through unvalidated; assuming hours are supported.","solutions":["Use one of exactly 'ns', 'us', 'ms', 's', 'd'","Normalise human unit names first: {'seconds':'s','secs':'s','milliseconds':'ms','microseconds':'us','nanoseconds':'ns','days':'d'}","For unsupported units like minutes/hours, derive from a supported one: .dt.epoch('s') // 60"],"exampleFix":"# before\npl.col('ts').dt.epoch('seconds')  # ValueError\n\n# after\npl.col('ts').dt.epoch('s')\n# minutes, derived: pl.col('ts').dt.epoch('s') // 60","handlingStrategy":"validation","validationCode":"VALID_EPOCH_UNITS = {'ns', 'us', 'ms', 's', 'd'}\nALIASES = {'seconds': 's', 'secs': 's', 'milliseconds': 'ms', 'microseconds': 'us', 'nanoseconds': 'ns', 'days': 'd'}\n\ntime_unit = ALIASES.get(time_unit, time_unit)\nif time_unit not in VALID_EPOCH_UNITS:\n    raise ValueError(f'time_unit must be one of {sorted(VALID_EPOCH_UNITS)}')\nexpr = pl.col('ts').dt.epoch(time_unit)","typeGuard":"from typing import Literal, TypeGuard\n\nEpochUnit = Literal['ns', 'us', 'ms', 's', 'd']\n\ndef is_epoch_unit(v: str) -> TypeGuard[EpochUnit]:\n    return v in ('ns', 'us', 'ms', 's', 'd')","tryCatchPattern":null,"preventionTips":["Type the parameter Literal['ns','us','ms','s','d']","Map human unit names to single-letter units before forwarding user input"],"tags":["datetime","time-unit","validation","epoch"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}