{"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":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1969,"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":1951,"sourceCodeEnd":1987,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1951-L1987","documentation":"Raised by DatetimeLikeArrayMixin.as_unit when the requested unit string is not one of the four supported numpy datetime/timedelta resolutions: 's', 'ms', 'us', 'ns'. pandas only stores sub-second precision down to nanoseconds and only exposes second-granularity as the coarsest supported unit, so coarser (e.g. 'm','h') or finer (e.g. 'ps') units are rejected.","triggerScenarios":"Calling .as_unit('m'), .as_unit('h'), .as_unit('ps'), or any non-listed string on a DatetimeIndex/TimedeltaIndex/DatetimeArray/TimedeltaArray.","commonSituations":"Assuming as_unit accepts the same vocabulary as numpy's time units; passing an IUPAC-style code; copy-pasting a unit string from a different library (e.g. arrow/pendulum).","solutions":["Map to the nearest supported unit: use 's' for minute/hour/day precision (precision is truncated up to second).","If you only need display formatting, format the timestamps as strings instead of changing the dtype unit.","For sub-nanosecond needs, keep the value as an integer count or use a custom dtype; pandas cannot store it."],"exampleFix":"// before\nidx = pd.date_range('2020-01-01', periods=3)\nidx.as_unit('m')  # ValueError: Supported units are 's', 'ms', 'us', 'ns'\n\n// after\nidx.as_unit('s')","handlingStrategy":"validation","validationCode":"SUPPORTED_UNITS = {\"s\",\"ms\",\"us\",\"ns\"}\ndef safe_as_unit(idx, unit):\n    if unit not in SUPPORTED_UNITS:\n        raise ValueError(f\"unit must be one of {SUPPORTED_UNITS}, got {unit!r}\")\n    return idx.as_unit(unit)","typeGuard":"def is_supported_unit(unit: str) -> bool:\n    return unit in {\"s\",\"ms\",\"us\",\"ns\"}","tryCatchPattern":"try:\n    out = idx.as_unit(unit)\nexcept ValueError as e:\n    if \"Supported units are\" in str(e):\n        out = idx.as_unit(\"s\")  # coarsest supported fallback\n    else:\n        raise","preventionTips":["Restrict user-configurable unit fields with an enum/allowlist.","Document the four supported units near any API exposing unit.","Normalize incoming unit strings to lowercase before validation."],"tags":["pandas","datetime","unit","resolution","validation"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}