def test_take_fill_valid(self, arr1d): arr = arr1d dti = self.index_cls(arr1d) dt_ind = Timestamp(2021, 1, 1, 12) dt_ind_tz = dt_ind.tz_localize(dti.tz) result = arr.take([-1, 1], allow_fill=True, fill_value=dt_ind_tz) assert result[0] == dt_ind_tz msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" with pytest.raises(TypeError, match=msg): # fill_value Timedelta invalid arr.take([-1, 1], allow_fill=True, fill_value=dt_ind_tz - dt_ind_tz) with pytest.raises(TypeError, match=msg): # fill_value Period invalid arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1")) tz = None if dti.tz is not None else "US/Eastern" dt_ind_tz = dt_ind.tz_localize(tz) msg = "Cannot compare tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): # Timestamp with mismatched tz-awareness arr.take([-1, 1], allow_fill=True, fill_value=dt_ind_tz) value = NaT.value msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" with pytest.raises(TypeError, match=msg): # require NaT, not iNaT, as it could be confused with an integer arr.take([-1, 1], allow_fill=True, fill_value=value) value = np.timedelta64("NaT", "ns") with pytest.raises(TypeError, match=msg): # require appropriate-dtype if we have a NA value arr.take([-1, 1], allow_fill=True, fill_value=value) if arr.tz is not None: # GH#37356 # Assuming here that arr1d fixture does not include Australia/Melbourne value = dt_ind.tz_localize("Australia/Melbourne") msg = "Timezones don't match. .* != 'Australia/Melbourne'" with pytest.raises(ValueError, match=msg): # require tz match, not just tzawareness match with tm.assert_produces_warning(FutureWarning, match="mismatched timezone"): result = arr.take([-1, 1], allow_fill=True, fill_value=value)
def _maybe_cast_for_get_loc(self, key) -> Timestamp: # needed to localize naive datetimes key = Timestamp(key) if key.tzinfo is None: key = key.tz_localize(self.tz) else: key = key.tz_convert(self.tz) return key
def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label Returns ------- loc : int """ if tolerance is not None: # try converting tolerance now, so errors don't get swallowed by # the try/except clauses below tolerance = self._convert_tolerance(tolerance, np.asarray(key)) if isinstance(key, datetime): # needed to localize naive datetimes if key.tzinfo is None: key = Timestamp(key, tz=self.tz) else: key = Timestamp(key).tz_convert(self.tz) return Index.get_loc(self, key, method, tolerance) elif isinstance(key, timedelta): # GH#20464 raise TypeError( f"Cannot index {type(self).__name__} with {type(key).__name__}" ) if isinstance(key, time): if method is not None: raise NotImplementedError( "cannot yet lookup inexact labels when key is a time object" ) return self.indexer_at_time(key) try: return Index.get_loc(self, key, method, tolerance) except (KeyError, ValueError, TypeError): try: return self._get_string_slice(key) except (TypeError, KeyError, ValueError, OverflowError): pass try: stamp = Timestamp(key) if stamp.tzinfo is not None and self.tz is not None: stamp = stamp.tz_convert(self.tz) else: stamp = stamp.tz_localize(self.tz) return Index.get_loc(self, stamp, method, tolerance) except KeyError: raise KeyError(key) except ValueError as e: # list-like tolerance size must match target index size if "list-like" in str(e): raise e raise KeyError(key)
def get_value_maybe_box(self, series, key): # needed to localize naive datetimes if self.tz is not None: key = Timestamp(key) if key.tzinfo is not None: key = key.tz_convert(self.tz) else: key = key.tz_localize(self.tz) elif not isinstance(key, Timestamp): key = Timestamp(key) values = self._engine.get_value(com.values_from_object(series), key, tz=self.tz) return com.maybe_box(self, values, series, key)
def _maybe_cast_for_get_loc(self, key) -> Timestamp: # needed to localize naive datetimes or dates (GH 35690) try: key = Timestamp(key) except ValueError as err: # FIXME(dateutil#1180): we get here because parse_with_reso # doesn't raise on "t2m" if not isinstance(key, str): # Not expected to be reached, but check to be sure raise # pragma: no cover raise KeyError(key) from err if key.tzinfo is None: key = key.tz_localize(self.tz) else: key = key.tz_convert(self.tz) return key
def _parsed_string_to_bounds(self, reso, parsed): """ Calculate datetime bounds for parsed time string and its resolution. Parameters ---------- reso : Resolution Resolution provided by parsed string. parsed : datetime Datetime from parsed string. Returns ------- lower, upper: pd.Timestamp """ valid_resos = { "year", "month", "quarter", "day", "hour", "minute", "second", "minute", "second", "microsecond", } if reso not in valid_resos: raise KeyError if reso == "year": start = Timestamp(parsed.year, 1, 1) end = Timestamp(parsed.year, 12, 31, 23, 59, 59, 999999) elif reso == "month": d = ccalendar.get_days_in_month(parsed.year, parsed.month) start = Timestamp(parsed.year, parsed.month, 1) end = Timestamp(parsed.year, parsed.month, d, 23, 59, 59, 999999) elif reso == "quarter": qe = (((parsed.month - 1) + 2) % 12) + 1 # two months ahead d = ccalendar.get_days_in_month(parsed.year, qe) # at end of month start = Timestamp(parsed.year, parsed.month, 1) end = Timestamp(parsed.year, qe, d, 23, 59, 59, 999999) elif reso == "day": start = Timestamp(parsed.year, parsed.month, parsed.day) end = start + timedelta(days=1) - Nano(1) elif reso == "hour": start = Timestamp(parsed.year, parsed.month, parsed.day, parsed.hour) end = start + timedelta(hours=1) - Nano(1) elif reso == "minute": start = Timestamp(parsed.year, parsed.month, parsed.day, parsed.hour, parsed.minute) end = start + timedelta(minutes=1) - Nano(1) elif reso == "second": start = Timestamp( parsed.year, parsed.month, parsed.day, parsed.hour, parsed.minute, parsed.second, ) end = start + timedelta(seconds=1) - Nano(1) elif reso == "microsecond": start = Timestamp( parsed.year, parsed.month, parsed.day, parsed.hour, parsed.minute, parsed.second, parsed.microsecond, ) end = start + timedelta(microseconds=1) - Nano(1) # GH 24076 # If an incoming date string contained a UTC offset, need to localize # the parsed date to this offset first before aligning with the index's # timezone if parsed.tzinfo is not None: if self.tz is None: raise ValueError( "The index must be timezone aware when indexing " "with a date string with a UTC offset") start = start.tz_localize(parsed.tzinfo).tz_convert(self.tz) end = end.tz_localize(parsed.tzinfo).tz_convert(self.tz) elif self.tz is not None: start = start.tz_localize(self.tz) end = end.tz_localize(self.tz) return start, end