diff --git a/pandas/_libs/tslibs/dtypes.pxd b/pandas/_libs/tslibs/dtypes.pxd index 352680143113d..11b92447f5011 100644 --- a/pandas/_libs/tslibs/dtypes.pxd +++ b/pandas/_libs/tslibs/dtypes.pxd @@ -8,6 +8,7 @@ cdef NPY_DATETIMEUNIT abbrev_to_npy_unit(str abbrev) cdef NPY_DATETIMEUNIT freq_group_code_to_npy_unit(int freq) nogil cpdef int64_t periods_per_day(NPY_DATETIMEUNIT reso=*) except? -1 cpdef int64_t periods_per_second(NPY_DATETIMEUNIT reso) except? -1 +cpdef NPY_DATETIMEUNIT get_supported_reso(NPY_DATETIMEUNIT reso) cdef dict attrname_to_abbrevs diff --git a/pandas/_libs/tslibs/dtypes.pyi b/pandas/_libs/tslibs/dtypes.pyi index 82f62e16c4205..a54db51136d07 100644 --- a/pandas/_libs/tslibs/dtypes.pyi +++ b/pandas/_libs/tslibs/dtypes.pyi @@ -9,6 +9,7 @@ def periods_per_day(reso: int) -> int: ... def periods_per_second(reso: int) -> int: ... def is_supported_unit(reso: int) -> bool: ... def npy_unit_to_abbrev(reso: int) -> str: ... +def get_supported_reso(reso: int) -> int: ... class PeriodDtypeBase: _dtype_code: int # PeriodDtypeCode diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx index 2f847640d606e..94781374296fa 100644 --- a/pandas/_libs/tslibs/dtypes.pyx +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -278,6 +278,19 @@ class NpyDatetimeUnit(Enum): NPY_FR_GENERIC = NPY_DATETIMEUNIT.NPY_FR_GENERIC +cpdef NPY_DATETIMEUNIT get_supported_reso(NPY_DATETIMEUNIT reso): + # If we have an unsupported reso, return the nearest supported reso. + if reso == NPY_DATETIMEUNIT.NPY_FR_GENERIC: + # TODO: or raise ValueError? trying this gives unraisable errors, but + # "except? -1" breaks at compile-time for unknown reasons + return NPY_DATETIMEUNIT.NPY_FR_ns + if reso < NPY_DATETIMEUNIT.NPY_FR_s: + return NPY_DATETIMEUNIT.NPY_FR_s + elif reso > NPY_DATETIMEUNIT.NPY_FR_ns: + return NPY_DATETIMEUNIT.NPY_FR_ns + return reso + + def is_supported_unit(NPY_DATETIMEUNIT reso): return ( reso == NPY_DATETIMEUNIT.NPY_FR_ns