From eaee6027c5fd46c239ba6018d214ed037da0246e Mon Sep 17 00:00:00 2001 From: MomIsBestFriend <> Date: Sat, 21 Mar 2020 17:54:52 +0200 Subject: [PATCH] CLN: pandas/_libs/tslibs/nattype.pyx --- pandas/_libs/tslibs/nattype.pyx | 232 +++++++++++++++++++------------- 1 file changed, 138 insertions(+), 94 deletions(-) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 7fec4ba5e7d25..ec397a470f2ec 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -1,10 +1,20 @@ from cpython.object cimport ( + Py_EQ, + Py_GE, + Py_GT, + Py_LE, + Py_LT, + Py_NE, PyObject_RichCompare, - Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE) +) -from cpython.datetime cimport (datetime, timedelta, - PyDateTime_Check, PyDelta_Check, - PyDateTime_IMPORT) +from cpython.datetime cimport ( + PyDateTime_Check, + PyDateTime_IMPORT, + PyDelta_Check, + datetime, + timedelta, +) from cpython.version cimport PY_MINOR_VERSION @@ -16,20 +26,19 @@ from numpy cimport int64_t cnp.import_array() from pandas._libs.tslibs.np_datetime cimport ( - get_datetime64_value, get_timedelta64_value) + get_datetime64_value, + get_timedelta64_value, +) cimport pandas._libs.tslibs.util as util -from pandas._libs.tslibs.util cimport ( - get_nat, is_integer_object, is_float_object, is_datetime64_object, - is_timedelta64_object) from pandas._libs.missing cimport C_NA # ---------------------------------------------------------------------- # Constants -nat_strings = {'NaT', 'nat', 'NAT', 'nan', 'NaN', 'NAN'} +nat_strings = {"NaT", "nat", "NAT", "nan", "NaN", "NAN"} -cdef int64_t NPY_NAT = get_nat() +cdef int64_t NPY_NAT = util.get_nat() iNaT = NPY_NAT # python-visible constant cdef bint _nat_scalar_rules[6] @@ -61,7 +70,7 @@ def _make_nat_func(func_name, doc): def _make_error_func(func_name, cls): def f(*args, **kwargs): - raise ValueError("NaTType does not support " + func_name) + raise ValueError(f"NaTType does not support {func_name}") f.__name__ = func_name if isinstance(cls, str): @@ -73,9 +82,9 @@ def _make_error_func(func_name, cls): cdef _nat_divide_op(self, other): - if PyDelta_Check(other) or is_timedelta64_object(other) or other is c_NaT: + if PyDelta_Check(other) or util.is_timedelta64_object(other) or other is c_NaT: return np.nan - if is_integer_object(other) or is_float_object(other): + if util.is_integer_object(other) or util.is_float_object(other): return c_NaT return NotImplemented @@ -103,7 +112,7 @@ cdef class _NaT(datetime): def __richcmp__(_NaT self, object other, int op): cdef: - int ndim = getattr(other, 'ndim', -1) + int ndim = getattr(other, "ndim", -1) if ndim == -1: return _nat_scalar_rules[op] @@ -114,11 +123,13 @@ cdef class _NaT(datetime): return result elif ndim == 0: - if is_datetime64_object(other): + if util.is_datetime64_object(other): return _nat_scalar_rules[op] else: - raise TypeError(f'Cannot compare type {type(self).__name__} ' - f'with type {type(other).__name__}') + raise TypeError( + f"Cannot compare type {type(self).__name__} " + f"with type {type(other).__name__}" + ) # Note: instead of passing "other, self, _reverse_ops[op]", we observe # that `_nat_scalar_rules` is invariant under `_reverse_ops`, @@ -134,19 +145,19 @@ cdef class _NaT(datetime): return c_NaT elif PyDelta_Check(other): return c_NaT - elif is_datetime64_object(other) or is_timedelta64_object(other): + elif util.is_datetime64_object(other) or util.is_timedelta64_object(other): return c_NaT - elif hasattr(other, 'delta'): + elif hasattr(other, "delta"): # Timedelta, offsets.Tick, offsets.Week return c_NaT - elif is_integer_object(other) or util.is_period_object(other): + elif util.is_integer_object(other) or util.is_period_object(other): # For Period compat # TODO: the integer behavior is deprecated, remove it return c_NaT elif util.is_array(other): - if other.dtype.kind in 'mM': + if other.dtype.kind in "mM": # If we are adding to datetime64, we treat NaT as timedelta # Either way, result dtype is datetime64 result = np.empty(other.shape, dtype="datetime64[ns]") @@ -171,19 +182,19 @@ cdef class _NaT(datetime): return c_NaT elif PyDelta_Check(other): return c_NaT - elif is_datetime64_object(other) or is_timedelta64_object(other): + elif util.is_datetime64_object(other) or util.is_timedelta64_object(other): return c_NaT - elif hasattr(other, 'delta'): + elif hasattr(other, "delta"): # offsets.Tick, offsets.Week return c_NaT - elif is_integer_object(other) or util.is_period_object(other): + elif util.is_integer_object(other) or util.is_period_object(other): # For Period compat # TODO: the integer behavior is deprecated, remove it return c_NaT elif util.is_array(other): - if other.dtype.kind == 'm': + if other.dtype.kind == "m": if not is_rsub: # NaT - timedelta64 we treat NaT as datetime64, so result # is datetime64 @@ -197,15 +208,16 @@ cdef class _NaT(datetime): result.fill("NaT") return result - elif other.dtype.kind == 'M': + elif other.dtype.kind == "M": # We treat NaT as a datetime, so regardless of whether this is # NaT - other or other - NaT, the result is timedelta64 result = np.empty(other.shape, dtype="timedelta64[ns]") result.fill("NaT") return result - raise TypeError(f"Cannot subtract NaT from ndarray with " - f"dtype {other.dtype}") + raise TypeError( + f"Cannot subtract NaT from ndarray with dtype {other.dtype}" + ) return NotImplemented @@ -225,19 +237,19 @@ cdef class _NaT(datetime): return _nat_divide_op(self, other) def __mul__(self, other): - if is_integer_object(other) or is_float_object(other): + if util.is_integer_object(other) or util.is_float_object(other): return NaT return NotImplemented @property def asm8(self) -> np.datetime64: - return np.datetime64(NPY_NAT, 'ns') + return np.datetime64(NPY_NAT, "ns") def to_datetime64(self) -> np.datetime64: """ Return a numpy.datetime64 object with 'ns' precision. """ - return np.datetime64('NaT', 'ns') + return np.datetime64('NaT', "ns") def to_numpy(self, dtype=None, copy=False) -> np.datetime64: """ @@ -260,14 +272,14 @@ cdef class _NaT(datetime): return self.to_datetime64() def __repr__(self) -> str: - return 'NaT' + return "NaT" def __str__(self) -> str: - return 'NaT' + return "NaT" - def isoformat(self, sep='T') -> str: + def isoformat(self, sep="T") -> str: # This allows Timestamp(ts.isoformat()) to always correctly roundtrip. - return 'NaT' + return "NaT" def __hash__(self): return NPY_NAT @@ -308,7 +320,9 @@ cdef class _NaT(datetime): class NaTType(_NaT): - """(N)ot-(A)-(T)ime, the time equivalent of NaN""" + """ + (N)ot-(A)-(T)ime, the time equivalent of NaN. + """ def __new__(cls): cdef _NaT base @@ -338,7 +352,7 @@ class NaTType(_NaT): return _nat_rdivide_op(self, other) def __rmul__(self, other): - if is_integer_object(other) or is_float_object(other): + if util.is_integer_object(other) or util.is_float_object(other): return c_NaT return NotImplemented @@ -379,10 +393,11 @@ class NaTType(_NaT): # These are the ones that can get their docstrings from datetime. # nan methods - weekday = _make_nan_func('weekday', datetime.weekday.__doc__) - isoweekday = _make_nan_func('isoweekday', datetime.isoweekday.__doc__) - total_seconds = _make_nan_func('total_seconds', timedelta.total_seconds.__doc__) - month_name = _make_nan_func('month_name', # noqa:E128 + weekday = _make_nan_func("weekday", datetime.weekday.__doc__) + isoweekday = _make_nan_func("isoweekday", datetime.isoweekday.__doc__) + total_seconds = _make_nan_func("total_seconds", timedelta.total_seconds.__doc__) + month_name = _make_nan_func( + "month_name", """ Return the month name of the Timestamp with specified locale. @@ -396,8 +411,10 @@ class NaTType(_NaT): month_name : string .. versionadded:: 0.23.0 - """) - day_name = _make_nan_func('day_name', # noqa:E128 + """, + ) + day_name = _make_nan_func( + "day_name", """ Return the day name of the Timestamp with specified locale. @@ -411,73 +428,79 @@ class NaTType(_NaT): day_name : string .. versionadded:: 0.23.0 - """) + """, + ) # _nat_methods - date = _make_nat_func('date', datetime.date.__doc__) - - utctimetuple = _make_error_func('utctimetuple', datetime) - timetz = _make_error_func('timetz', datetime) - timetuple = _make_error_func('timetuple', datetime) - strftime = _make_error_func('strftime', datetime) - isocalendar = _make_error_func('isocalendar', datetime) - dst = _make_error_func('dst', datetime) - ctime = _make_error_func('ctime', datetime) - time = _make_error_func('time', datetime) - toordinal = _make_error_func('toordinal', datetime) - tzname = _make_error_func('tzname', datetime) - utcoffset = _make_error_func('utcoffset', datetime) + date = _make_nat_func("date", datetime.date.__doc__) + + utctimetuple = _make_error_func("utctimetuple", datetime) + timetz = _make_error_func("timetz", datetime) + timetuple = _make_error_func("timetuple", datetime) + strftime = _make_error_func("strftime", datetime) + isocalendar = _make_error_func("isocalendar", datetime) + dst = _make_error_func("dst", datetime) + ctime = _make_error_func("ctime", datetime) + time = _make_error_func("time", datetime) + toordinal = _make_error_func("toordinal", datetime) + tzname = _make_error_func("tzname", datetime) + utcoffset = _make_error_func("utcoffset", datetime) # "fromisocalendar" was introduced in 3.8 if PY_MINOR_VERSION >= 8: - fromisocalendar = _make_error_func('fromisocalendar', datetime) + fromisocalendar = _make_error_func("fromisocalendar", datetime) # ---------------------------------------------------------------------- # The remaining methods have docstrings copy/pasted from the analogous # Timestamp methods. - strptime = _make_error_func('strptime', # noqa:E128 + strptime = _make_error_func( + "strptime", """ Timestamp.strptime(string, format) Function is not implemented. Use pd.to_datetime(). - """ + """, ) - utcfromtimestamp = _make_error_func('utcfromtimestamp', # noqa:E128 + utcfromtimestamp = _make_error_func( + "utcfromtimestamp", """ Timestamp.utcfromtimestamp(ts) Construct a naive UTC datetime from a POSIX timestamp. - """ + """, ) - fromtimestamp = _make_error_func('fromtimestamp', # noqa:E128 + fromtimestamp = _make_error_func( + "fromtimestamp", """ Timestamp.fromtimestamp(ts) timestamp[, tz] -> tz's local time from POSIX timestamp. - """ + """, ) - combine = _make_error_func('combine', # noqa:E128 + combine = _make_error_func( + "combine", """ Timestamp.combine(date, time) date, time -> datetime with same date and time fields. - """ + """, ) - utcnow = _make_error_func('utcnow', # noqa:E128 + utcnow = _make_error_func( + "utcnow", """ Timestamp.utcnow() Return a new Timestamp representing UTC day and time. - """ + """, ) - timestamp = _make_error_func('timestamp', # noqa:E128 - """Return POSIX timestamp as float.""") + timestamp = _make_error_func("timestamp", "Return POSIX timestamp as float.") # GH9513 NaT methods (except to_datetime64) to raise, return np.nan, or # return NaT create functions that raise, for binding to NaTType - astimezone = _make_error_func('astimezone', # noqa:E128 + astimezone = _make_error_func( + "astimezone", """ Convert tz-aware Timestamp to another time zone. @@ -495,8 +518,10 @@ class NaTType(_NaT): ------ TypeError If Timestamp is tz-naive. - """) - fromordinal = _make_error_func('fromordinal', # noqa:E128 + """, + ) + fromordinal = _make_error_func( + "fromordinal", """ Timestamp.fromordinal(ordinal, freq=None, tz=None) @@ -511,17 +536,21 @@ class NaTType(_NaT): Offset to apply to the Timestamp. tz : str, pytz.timezone, dateutil.tz.tzfile or None Time zone for the Timestamp. - """) + """, + ) # _nat_methods - to_pydatetime = _make_nat_func('to_pydatetime', # noqa:E128 + to_pydatetime = _make_nat_func( + "to_pydatetime", """ Convert a Timestamp object to a native Python datetime object. If warn=True, issue a warning if nanoseconds is nonzero. - """) + """, + ) - now = _make_nat_func('now', # noqa:E128 + now = _make_nat_func( + "now", """ Timestamp.now(tz=None) @@ -532,8 +561,10 @@ class NaTType(_NaT): ---------- tz : str or timezone object, default None Timezone to localize to. - """) - today = _make_nat_func('today', # noqa:E128 + """, + ) + today = _make_nat_func( + "today", """ Timestamp.today(cls, tz=None) @@ -545,8 +576,10 @@ class NaTType(_NaT): ---------- tz : str or timezone object, default None Timezone to localize to. - """) - round = _make_nat_func('round', # noqa:E128 + """, + ) + round = _make_nat_func( + "round", """ Round the Timestamp to the specified resolution. @@ -586,8 +619,10 @@ timedelta}, default 'raise' Raises ------ ValueError if the freq cannot be converted - """) - floor = _make_nat_func('floor', # noqa:E128 + """, + ) + floor = _make_nat_func( + "floor", """ return a new Timestamp floored to this resolution. @@ -623,8 +658,10 @@ timedelta}, default 'raise' Raises ------ ValueError if the freq cannot be converted. - """) - ceil = _make_nat_func('ceil', # noqa:E128 + """, + ) + ceil = _make_nat_func( + "ceil", """ return a new Timestamp ceiled to this resolution. @@ -660,9 +697,11 @@ timedelta}, default 'raise' Raises ------ ValueError if the freq cannot be converted. - """) + """, + ) - tz_convert = _make_nat_func('tz_convert', # noqa:E128 + tz_convert = _make_nat_func( + "tz_convert", """ Convert tz-aware Timestamp to another time zone. @@ -680,8 +719,10 @@ timedelta}, default 'raise' ------ TypeError If Timestamp is tz-naive. - """) - tz_localize = _make_nat_func('tz_localize', # noqa:E128 + """, + ) + tz_localize = _make_nat_func( + "tz_localize", """ Convert naive Timestamp to local time zone, or remove timezone from tz-aware Timestamp. @@ -733,8 +774,10 @@ default 'raise' ------ TypeError If the Timestamp is tz-aware and tz is not None. - """) - replace = _make_nat_func('replace', # noqa:E128 + """, + ) + replace = _make_nat_func( + "replace", """ implements datetime.replace, handles nanoseconds. @@ -754,7 +797,8 @@ default 'raise' Returns ------- Timestamp with fields replaced - """) + """, + ) c_NaT = NaTType() # C-visible @@ -772,7 +816,7 @@ cdef inline bint checknull_with_nat(object val): cpdef bint is_null_datetimelike(object val, bint inat_is_null=True): """ - Determine if we have a null for a timedelta/datetime (or integer versions) + Determine if we have a null for a timedelta/datetime (or integer versions). Parameters ---------- @@ -782,7 +826,7 @@ cpdef bint is_null_datetimelike(object val, bint inat_is_null=True): Returns ------- - null_datetimelike : bool + bool """ if val is None: return True