{"record":{"id":"a9cc291b7bb66c6e","repo":"pandas-dev/pandas","slug":"supported-units-are-s-ms-us-ns","errorCode":null,"errorMessage":"Supported units are 's', 'ms', 'us', 'ns'","messagePattern":"Supported units are 's', 'ms', 'us', 'ns'","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1956,"sourceCode":"\n        >>> idx = pd.DatetimeIndex([\"2020-01-02 01:02:03.004005006\"])\n        >>> idx\n        DatetimeIndex(['2020-01-02 01:02:03.004005006'],\n                      dtype='datetime64[ns]', freq=None)\n        >>> idx.as_unit(\"s\")\n        DatetimeIndex(['2020-01-02 01:02:03'], dtype='datetime64[s]', freq=None)\n\n        For :class:`pandas.TimedeltaIndex`:\n\n        >>> tdelta_idx = pd.to_timedelta([\"1 day 3 min 2 us 42 ns\"])\n        >>> tdelta_idx\n        TimedeltaIndex(['1 days 00:03:00.000002042'],\n                        dtype='timedelta64[ns]', freq=None)\n        >>> tdelta_idx.as_unit(\"s\")\n        TimedeltaIndex(['1 days 00:03:00'], dtype='timedelta64[s]', freq=None)\n        \"\"\"\n        if unit not in [\"s\", \"ms\", \"us\", \"ns\"]:\n            raise ValueError(\"Supported units are 's', 'ms', 'us', 'ns'\")\n\n        dtype = np.dtype(f\"{self.dtype.kind}8[{unit}]\")\n        new_values = astype_overflowsafe(self._ndarray, dtype, round_ok=round_ok)\n\n        if isinstance(self.dtype, np.dtype):\n            new_dtype = new_values.dtype\n        else:\n            tz = cast(\"DatetimeArray\", self).tz\n            new_dtype = DatetimeTZDtype(tz=tz, unit=unit)\n\n        return type(self)._simple_new(\n            new_values,\n            dtype=new_dtype,\n        )\n\n    # TODO: annotate other as DatetimeArray | TimedeltaArray | Timestamp | Timedelta\n    #  with the return type matching input type.  TypeVar?\n    def _ensure_matching_resos(self, other):","sourceCodeStart":1938,"sourceCodeEnd":1974,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1938-L1974","documentation":"Raised by DatetimeLikeArrayMixin.as_unit when the requested unit is not one of the four supported time resolutions. pandas datetime/timedelta storage only supports seconds, milliseconds, microseconds, and nanoseconds; finer (e.g. picoseconds) or coarser (minutes, hours) units are not valid internal storage units, though they may appear as frequencies.","triggerScenarios":"idx.as_unit('m') (intending minutes), idx.as_unit('us5'), idx.as_unit('ps'), or passing an offset alias like 'h'/'T' to as_unit. Also reached by Series.dt.as_unit with the wrong alias.","commonSituations":"Confusing frequency aliases ('T'/'min', 'h') with storage units. Reading code that uses numpy-style unit strings. Wanting sub-nanosecond precision from Arrow-backed data.","solutions":["Pass one of 's', 'ms', 'us', 'ns' to as_unit.","If you wanted minute/hourly spacing, that is a frequency — use .asfreq() / date_range(freq=...) instead of as_unit.","If you need finer-than-nanosecond resolution, use a pyarrow-backed dtype (pd.ArrowDtype(pa.timestamp('ns'))) — picosecond storage is still unsupported."],"exampleFix":"# before\nidx.as_unit('m')\n\n# after (minutes are a frequency, not a storage unit)\nidx.as_unit('s')            # coarsest storage unit\nidx.asfreq('min')           # resample to a minute grid","handlingStrategy":"validation","validationCode":"VALID_UNITS = {'s','ms','us','ns'}\nif unit not in VALID_UNITS:\n    raise ValueError(f'unit must be one of {VALID_UNITS}, got {unit!r}')","typeGuard":"from typing import Literal\ndef is_valid_time_unit(u: str) -> bool:\n    return u in {'s','ms','us','ns'}\n# or: isinstance guard via Literal['s','ms','us','ns']","tryCatchPattern":"try:\n    idx.as_unit(unit)\nexcept ValueError as e:\n    if 'Supported units are' in str(e):\n        idx.as_unit('ns')\n    else: raise","preventionTips":["Keep unit strings as a single Literal-typed constant in your config layer.","Remember: minutes/hours are freq aliases, not storage units."],"tags":["datetime","timedelta","unit","resolution","validation"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}