Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DEPR: disallow tznaive datetimes when indexing tzaware datetimeindex #36148

Merged
merged 14 commits into from
Oct 7, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,10 @@ def get_loc(self, key, method=None, tolerance=None):

if isinstance(key, self._data._recognized_scalars):
# needed to localize naive datetimes
try:
self._data._assert_tzawareness_compat(key)
except TypeError as err:
raise KeyError(key) from err
key = self._maybe_cast_for_get_loc(key)

elif isinstance(key, str):
Expand Down Expand Up @@ -654,6 +658,10 @@ def _maybe_cast_slice_bound(self, label, side: str, kind):
-------
label : object

Raises
------
TypeError : indexing timezone-aware DatetimeIndex with tz-naive datetime

Notes
-----
Value of `side` parameter should be validated in caller.
Expand All @@ -677,6 +685,8 @@ def _maybe_cast_slice_bound(self, label, side: str, kind):
if self._is_strictly_monotonic_decreasing and len(self) > 1:
return upper if side == "left" else lower
return lower if side == "left" else upper
elif isinstance(label, (self._data._recognized_scalars, date)):
self._data._assert_tzawareness_compat(label)
return self._maybe_cast_for_get_loc(label)

def _get_string_slice(self, key: str, use_lhs: bool = True, use_rhs: bool = True):
Expand Down
50 changes: 34 additions & 16 deletions pandas/tests/indexes/datetimes/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,11 +675,17 @@ def test_get_slice_bounds_datetime_within(
self, box, kind, side, expected, tz_aware_fixture
):
# GH 35690
index = bdate_range("2000-01-03", "2000-02-11").tz_localize(tz_aware_fixture)
result = index.get_slice_bound(
box(year=2000, month=1, day=7), kind=kind, side=side
)
assert result == expected
tz = tz_aware_fixture
index = bdate_range("2000-01-03", "2000-02-11").tz_localize(tz)
key = box(year=2000, month=1, day=7)
if tz is None:
result = index.get_slice_bound(key, kind=kind, side=side)
assert result == expected
else:
# We require tzawareness-compat in indexing
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
index.get_slice_bound(key, kind=kind, side=side)

@pytest.mark.parametrize("box", [date, datetime, Timestamp])
@pytest.mark.parametrize("kind", ["getitem", "loc", None])
Expand All @@ -689,19 +695,31 @@ def test_get_slice_bounds_datetime_outside(
self, box, kind, side, year, expected, tz_aware_fixture
):
# GH 35690
index = bdate_range("2000-01-03", "2000-02-11").tz_localize(tz_aware_fixture)
result = index.get_slice_bound(
box(year=year, month=1, day=7), kind=kind, side=side
)
assert result == expected
tz = tz_aware_fixture
index = bdate_range("2000-01-03", "2000-02-11").tz_localize(tz)
key = box(year=year, month=1, day=7)
if tz is None:
result = index.get_slice_bound(key, kind=kind, side=side)
assert result == expected
else:
# We require tzawareness compat in indexing
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
index.get_slice_bound(key, kind=kind, side=side)

@pytest.mark.parametrize("box", [date, datetime, Timestamp])
@pytest.mark.parametrize("kind", ["getitem", "loc", None])
def test_slice_datetime_locs(self, box, kind, tz_aware_fixture):
# GH 34077
index = DatetimeIndex(["2010-01-01", "2010-01-03"]).tz_localize(
tz_aware_fixture
)
result = index.slice_locs(box(2010, 1, 1), box(2010, 1, 2))
expected = (0, 1)
assert result == expected
tz = tz_aware_fixture
index = DatetimeIndex(["2010-01-01", "2010-01-03"]).tz_localize(tz)
key = box(2010, 1, 1)
if tz is None:
result = index.slice_locs(key, box(2010, 1, 2))
expected = (0, 1)
assert result == expected
else:
# We require tzawareness-compat in indexing
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
index.slice_locs(key, box(2010, 1, 2))
36 changes: 19 additions & 17 deletions pandas/tests/series/indexing/test_datetime.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
"""
Also test support for datetime64[ns] in Series / DataFrame
"""
from datetime import datetime, timedelta
import re

Expand All @@ -11,10 +14,6 @@
from pandas import DataFrame, DatetimeIndex, NaT, Series, Timestamp, date_range
import pandas._testing as tm

"""
Also test support for datetime64[ns] in Series / DataFrame
"""


def test_fancy_getitem():
dti = date_range(
Expand Down Expand Up @@ -238,24 +237,27 @@ def test_getitem_setitem_datetimeindex():
expected = ts[4:8]
tm.assert_series_equal(result, expected)

# repeat all the above with naive datetimes
result = ts[datetime(1990, 1, 1, 4)]
expected = ts[4]
assert result == expected
# But we do not give datetimes a pass on tzawareness compat
# TODO: do the same with Timestamps and dt64
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
naive = datetime(1990, 1, 1, 4)
with pytest.raises(KeyError, match=re.escape(repr(naive))):
ts[naive]

result = ts.copy()
result[datetime(1990, 1, 1, 4)] = 0
result[datetime(1990, 1, 1, 4)] = ts[4]
tm.assert_series_equal(result, ts)
with pytest.raises(TypeError, match=msg):
result[datetime(1990, 1, 1, 4)] = 0
with pytest.raises(TypeError, match=msg):
result[datetime(1990, 1, 1, 4)] = ts[4]

result = ts[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)]
expected = ts[4:8]
tm.assert_series_equal(result, expected)
with pytest.raises(TypeError, match=msg):
ts[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)]

result = ts.copy()
result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = 0
result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = ts[4:8]
tm.assert_series_equal(result, ts)
with pytest.raises(TypeError, match=msg):
result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = 0
with pytest.raises(TypeError, match=msg):
result[datetime(1990, 1, 1, 4) : datetime(1990, 1, 1, 7)] = ts[4:8]

lb = datetime(1990, 1, 1, 4)
rb = datetime(1990, 1, 1, 7)
Expand Down
8 changes: 7 additions & 1 deletion pandas/tests/series/methods/test_truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,13 @@ def test_truncate_datetimeindex_tz(self):
# GH 9243
idx = date_range("4/1/2005", "4/30/2005", freq="D", tz="US/Pacific")
s = Series(range(len(idx)), index=idx)
result = s.truncate(datetime(2005, 4, 2), datetime(2005, 4, 4))
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
with pytest.raises(TypeError, match=msg):
s.truncate(datetime(2005, 4, 2), datetime(2005, 4, 4))

lb = idx[1]
ub = idx[3]
result = s.truncate(lb.to_pydatetime(), ub.to_pydatetime())
expected = Series([1, 2, 3], index=idx[1:4])
tm.assert_series_equal(result, expected)

Expand Down