Skip to content

Commit 2667178

Browse files
committed
Fix: Indexing with dates of higher resolution should return empty slice instead raising KeyError
1 parent db31f6a commit 2667178

File tree

3 files changed

+10
-11
lines changed

3 files changed

+10
-11
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -971,6 +971,7 @@ Datetimelike
971971
- Bug in constructing arrays with :class:`ArrowDtype` with ``timestamp`` type incorrectly allowing ``Decimal("NaN")`` (:issue:`61773`)
972972
- Bug in constructing arrays with a timezone-aware :class:`ArrowDtype` from timezone-naive datetime objects incorrectly treating those as UTC times instead of wall times like :class:`DatetimeTZDtype` (:issue:`61775`)
973973
- Bug in setting scalar values with mismatched resolution into arrays with non-nanosecond ``datetime64``, ``timedelta64`` or :class:`DatetimeTZDtype` incorrectly truncating those scalars (:issue:`56410`)
974+
- Bug in :class:`DatetimeIndex` returning KeyError for out of range, failing to return empty slice when the resolution is greater than the current datetime objects. (:issue:`25803`)
974975

975976
Timedelta
976977
^^^^^^^^^

pandas/core/indexes/datetimelike.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -317,15 +317,8 @@ def _partial_date_slice(
317317
unbox = self._data._unbox
318318

319319
if self.is_monotonic_increasing:
320-
if len(self) and (
321-
(t1 < self[0] and t2 < self[0]) or (t1 > self[-1] and t2 > self[-1])
322-
):
323-
# we are out of range
324-
raise KeyError
325-
326-
# TODO: does this depend on being monotonic _increasing_?
327-
328-
# a monotonic (sorted) series can be sliced
320+
# a monotonic (sorted) series can be searched in ologn
321+
# if date is not found, the empty slice will be returned
329322
left = vals.searchsorted(unbox(t1), side="left")
330323
right = vals.searchsorted(unbox(t2), side="right")
331324
return slice(left, right)

pandas/tests/indexes/datetimes/test_partial_slicing.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,8 +247,13 @@ def test_partial_slice_second_precision(self):
247247
tm.assert_series_equal(s["2005-1-1 00:01:00"], s.iloc[10:])
248248

249249
assert s[Timestamp("2005-1-1 00:00:59.999990")] == s.iloc[0]
250-
with pytest.raises(KeyError, match="2005-1-1 00:00:00"):
251-
s["2005-1-1 00:00:00"]
250+
tm.assert_series_equal(s["2005-1-1 00:00:00"], s.iloc[0:0])
251+
252+
def test_partial_slice_higher_precision_empty(self):
253+
#GH25803
254+
s = Series([1, 2, 3], DatetimeIndex(['2018-01-01T01:01', '2018-02-02T01:01', '2018-02-02T02:02']))
255+
tm.assert_series_equal(s.loc['2018-03-03'], s.iloc[0:0])
256+
assert (s.loc['2018-03-03'].size == 0)
252257

253258
def test_partial_slicing_dataframe(self):
254259
# GH14856

0 commit comments

Comments
 (0)