Skip to content

Commit 94cdc16

Browse files
jbrockmendeljreback
authored andcommitted
Fix tzawareness_compat for DatetimeIndex comparisons with NaT (#19276)
1 parent c9532f0 commit 94cdc16

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

doc/source/whatsnew/v0.23.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ Conversion
430430
-
431431
- Bug in ``.astype()`` to non-ns timedelta units would hold the incorrect dtype (:issue:`19176`, :issue:`19223`, :issue:`12425`)
432432
- Bug in subtracting :class:`Series` from ``NaT`` incorrectly returning ``NaT`` (:issue:`19158`)
433-
433+
- Bug in comparison of timezone-aware :class:`DatetimeIndex` against ``NaT`` incorrectly raising ``TypeError`` (:issue:`19276`)
434434

435435
Indexing
436436
^^^^^^^^

pandas/core/indexes/datetimes.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,10 @@ def _assert_tzawareness_compat(self, other):
665665
if is_datetime64tz_dtype(other):
666666
# Get tzinfo from Series dtype
667667
other_tz = other.dtype.tz
668-
if self.tz is None:
668+
if other is libts.NaT:
669+
# pd.NaT quacks both aware and naive
670+
pass
671+
elif self.tz is None:
669672
if other_tz is not None:
670673
raise TypeError('Cannot compare tz-naive and tz-aware '
671674
'datetime-like objects.')

pandas/tests/indexes/datetimes/test_datetime.py

+15
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,21 @@ def test_comparison_tzawareness_compat(self, op):
286286
with pytest.raises(TypeError):
287287
op(dz, ts)
288288

289+
@pytest.mark.parametrize('op', [operator.eq, operator.ne,
290+
operator.gt, operator.ge,
291+
operator.lt, operator.le])
292+
def test_nat_comparison_tzawareness(self, op):
293+
# GH#19276
294+
# tzaware DatetimeIndex should not raise when compared to NaT
295+
dti = pd.DatetimeIndex(['2014-01-01', pd.NaT, '2014-03-01', pd.NaT,
296+
'2014-05-01', '2014-07-01'])
297+
expected = np.array([op == operator.ne] * len(dti))
298+
result = op(dti, pd.NaT)
299+
tm.assert_numpy_array_equal(result, expected)
300+
301+
result = op(dti.tz_localize('US/Pacific'), pd.NaT)
302+
tm.assert_numpy_array_equal(result, expected)
303+
289304
def test_comparisons_coverage(self):
290305
rng = date_range('1/1/2000', periods=10)
291306

0 commit comments

Comments
 (0)