Convert to a dtype with the given unit resolution. The limits of timestamp representation depend on the chosen resolution. Different resolutions can be converted to each other through as_unit. Parameters ---------- unit : {'s', 'ms', 'us', 'ns'}
(self, unit: TimeUnit, round_ok: bool = True)
| 2008 | return dtype_to_unit(self.dtype) # type: ignore[return-value,arg-type] |
| 2009 | |
| 2010 | def as_unit(self, unit: TimeUnit, round_ok: bool = True) -> Self: |
| 2011 | """ |
| 2012 | Convert to a dtype with the given unit resolution. |
| 2013 | |
| 2014 | The limits of timestamp representation depend on the chosen resolution. |
| 2015 | Different resolutions can be converted to each other through as_unit. |
| 2016 | |
| 2017 | Parameters |
| 2018 | ---------- |
| 2019 | unit : {'s', 'ms', 'us', 'ns'} |
| 2020 | round_ok : bool, default True |
| 2021 | If False and the conversion requires rounding, raise ValueError. |
| 2022 | |
| 2023 | Returns |
| 2024 | ------- |
| 2025 | same type as self |
| 2026 | Converted to the specified unit. |
| 2027 | |
| 2028 | See Also |
| 2029 | -------- |
| 2030 | Timestamp.as_unit : Convert to the given unit. |
| 2031 | |
| 2032 | Examples |
| 2033 | -------- |
| 2034 | For :class:`pandas.DatetimeIndex`: |
| 2035 | |
| 2036 | >>> idx = pd.DatetimeIndex(["2020-01-02 01:02:03.004005006"]) |
| 2037 | >>> idx |
| 2038 | DatetimeIndex(['2020-01-02 01:02:03.004005006'], |
| 2039 | dtype='datetime64[ns]', freq=None) |
| 2040 | >>> idx.as_unit("s") |
| 2041 | DatetimeIndex(['2020-01-02 01:02:03'], dtype='datetime64[s]', freq=None) |
| 2042 | |
| 2043 | For :class:`pandas.TimedeltaIndex`: |
| 2044 | |
| 2045 | >>> tdelta_idx = pd.to_timedelta(["1 day 3 min 2 us 42 ns"]) |
| 2046 | >>> tdelta_idx |
| 2047 | TimedeltaIndex(['1 days 00:03:00.000002042'], |
| 2048 | dtype='timedelta64[ns]', freq=None) |
| 2049 | >>> tdelta_idx.as_unit("s") |
| 2050 | TimedeltaIndex(['1 days 00:03:00'], dtype='timedelta64[s]', freq=None) |
| 2051 | """ |
| 2052 | if unit not in ["s", "ms", "us", "ns"]: |
| 2053 | raise ValueError("Supported units are 's', 'ms', 'us', 'ns'") |
| 2054 | |
| 2055 | dtype = np.dtype(f"{self.dtype.kind}8[{unit}]") |
| 2056 | new_values = astype_overflowsafe(self._ndarray, dtype, round_ok=round_ok) |
| 2057 | |
| 2058 | if isinstance(self.dtype, np.dtype): |
| 2059 | new_dtype = new_values.dtype |
| 2060 | else: |
| 2061 | tz = cast("DatetimeArray", self).tz |
| 2062 | new_dtype = DatetimeTZDtype(tz=tz, unit=unit) |
| 2063 | |
| 2064 | # error: Unexpected keyword argument "freq" for "_simple_new" of |
| 2065 | # "NDArrayBacked" [call-arg] |
| 2066 | return type(self)._simple_new( |
| 2067 | new_values, |