Skip to content

Commit ada928f

Browse files
committed
BUG: cannot subtract Timestamp with different timezones (pandas-dev#31793)
1 parent 04b538a commit ada928f

File tree

7 files changed

+112
-35
lines changed

7 files changed

+112
-35
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -632,6 +632,7 @@ Timezones
632632
^^^^^^^^^
633633
- Bug in :func:`to_datetime` with ``infer_datetime_format=True`` failing to parse zero UTC offset (``Z``) correctly (:issue:`41047`)
634634
- Bug in :meth:`Series.dt.tz_convert` resetting index in a :class:`Series` with :class:`CategoricalIndex` (:issue:`43080`)
635+
- Bug in ``Timestamp`` and ``DatetimeIndex`` incorrectly raising a ``TypeError`` when subtracting two timezone-aware objects with mismatched timezones (:issue:`31793`)
635636
-
636637

637638
Numeric

pandas/_libs/tslibs/timestamps.pyx

+4-4
Original file line numberDiff line numberDiff line change
@@ -343,10 +343,10 @@ cdef class _Timestamp(ABCTimestamp):
343343
else:
344344
self = type(other)(self)
345345

346-
# validate tz's
347-
if not tz_compare(self.tzinfo, other.tzinfo):
348-
raise TypeError("Timestamp subtraction must have the "
349-
"same timezones or no timezones")
346+
if (self.tzinfo is None) ^ (other.tzinfo is None):
347+
raise TypeError(
348+
"Cannot subtract tz-naive and tz-aware datetime-like objects."
349+
)
350350

351351
# scalar Timestamp/datetime - Timestamp/datetime -> yields a
352352
# Timedelta

pandas/core/arrays/datetimes.py

+10-11
Original file line numberDiff line numberDiff line change
@@ -728,12 +728,11 @@ def _sub_datetime_arraylike(self, other):
728728
assert is_datetime64_dtype(other)
729729
other = type(self)(other)
730730

731-
if not self._has_same_tz(other):
732-
# require tz compat
733-
raise TypeError(
734-
f"{type(self).__name__} subtraction must have the same "
735-
"timezones or no timezones"
736-
)
731+
try:
732+
self._assert_tzawareness_compat(other)
733+
except TypeError as error:
734+
new_message = str(error).replace("compare", "subtract")
735+
raise type(error)(new_message) from error
737736

738737
self_i8 = self.asi8
739738
other_i8 = other.asi8
@@ -779,11 +778,11 @@ def _sub_datetimelike_scalar(self, other):
779778
if other is NaT: # type: ignore[comparison-overlap]
780779
return self - NaT
781780

782-
if not self._has_same_tz(other):
783-
# require tz compat
784-
raise TypeError(
785-
"Timestamp subtraction must have the same timezones or no timezones"
786-
)
781+
try:
782+
self._assert_tzawareness_compat(other)
783+
except TypeError as error:
784+
new_message = str(error).replace("compare", "subtract")
785+
raise type(error)(new_message) from error
787786

788787
i8 = self.asi8
789788
result = checked_add_with_arr(i8, -other.value, arr_mask=self._isnan)

pandas/tests/arithmetic/test_datetime64.py

+57-6
Original file line numberDiff line numberDiff line change
@@ -843,6 +843,61 @@ def test_dt64arr_sub_timedeltalike_scalar(
843843
rng -= two_hours
844844
tm.assert_equal(rng, expected)
845845

846+
def test_dt64_array_sub_dt_with_different_timezone(self, box_with_array):
847+
t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
848+
t1 = tm.box_expected(t1, box_with_array)
849+
t2 = Timestamp("20130101").tz_localize("CET")
850+
tnaive = Timestamp(20130101)
851+
852+
result = t1 - t2
853+
expected = TimedeltaIndex(
854+
["0 days 06:00:00", "1 days 06:00:00", "2 days 06:00:00"]
855+
)
856+
expected = tm.box_expected(expected, box_with_array)
857+
tm.assert_equal(result, expected)
858+
859+
result = t2 - t1
860+
expected = TimedeltaIndex(
861+
["-1 days +18:00:00", "-2 days +18:00:00", "-3 days +18:00:00"]
862+
)
863+
expected = tm.box_expected(expected, box_with_array)
864+
tm.assert_equal(result, expected)
865+
866+
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
867+
with pytest.raises(TypeError, match=msg):
868+
t1 - tnaive
869+
870+
with pytest.raises(TypeError, match=msg):
871+
tnaive - t1
872+
873+
def test_dt64_array_sub_dt64_array_with_different_timezone(self, box_with_array):
874+
t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
875+
t1 = tm.box_expected(t1, box_with_array)
876+
t2 = date_range("20130101", periods=3).tz_localize("CET")
877+
t2 = tm.box_expected(t2, box_with_array)
878+
tnaive = date_range("20130101", periods=3)
879+
880+
result = t1 - t2
881+
expected = TimedeltaIndex(
882+
["0 days 06:00:00", "0 days 06:00:00", "0 days 06:00:00"]
883+
)
884+
expected = tm.box_expected(expected, box_with_array)
885+
tm.assert_equal(result, expected)
886+
887+
result = t2 - t1
888+
expected = TimedeltaIndex(
889+
["-1 days +18:00:00", "-1 days +18:00:00", "-1 days +18:00:00"]
890+
)
891+
expected = tm.box_expected(expected, box_with_array)
892+
tm.assert_equal(result, expected)
893+
894+
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
895+
with pytest.raises(TypeError, match=msg):
896+
t1 - tnaive
897+
898+
with pytest.raises(TypeError, match=msg):
899+
tnaive - t1
900+
846901
# TODO: redundant with test_dt64arr_add_timedeltalike_scalar
847902
def test_dt64arr_add_td64_scalar(self, box_with_array):
848903
# scalar timedeltas/np.timedelta64 objects
@@ -1024,7 +1079,7 @@ def test_dt64arr_aware_sub_dt64ndarray_raises(
10241079
dt64vals = dti.values
10251080

10261081
dtarr = tm.box_expected(dti, box_with_array)
1027-
msg = "subtraction must have the same timezones or"
1082+
msg = "Cannot subtract tz-naive and tz-aware datetime"
10281083
with pytest.raises(TypeError, match=msg):
10291084
dtarr - dt64vals
10301085
with pytest.raises(TypeError, match=msg):
@@ -2208,24 +2263,20 @@ def test_sub_dti_dti(self):
22082263

22092264
dti = date_range("20130101", periods=3)
22102265
dti_tz = date_range("20130101", periods=3).tz_localize("US/Eastern")
2211-
dti_tz2 = date_range("20130101", periods=3).tz_localize("UTC")
22122266
expected = TimedeltaIndex([0, 0, 0])
22132267

22142268
result = dti - dti
22152269
tm.assert_index_equal(result, expected)
22162270

22172271
result = dti_tz - dti_tz
22182272
tm.assert_index_equal(result, expected)
2219-
msg = "DatetimeArray subtraction must have the same timezones or"
2273+
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
22202274
with pytest.raises(TypeError, match=msg):
22212275
dti_tz - dti
22222276

22232277
with pytest.raises(TypeError, match=msg):
22242278
dti - dti_tz
22252279

2226-
with pytest.raises(TypeError, match=msg):
2227-
dti_tz - dti_tz2
2228-
22292280
# isub
22302281
dti -= dti
22312282
tm.assert_index_equal(dti, expected)

pandas/tests/arithmetic/test_timedelta64.py

+3-9
Original file line numberDiff line numberDiff line change
@@ -387,35 +387,29 @@ def _check(result, expected):
387387
_check(result, expected)
388388

389389
# tz mismatches
390-
msg = "Timestamp subtraction must have the same timezones or no timezones"
390+
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
391391
with pytest.raises(TypeError, match=msg):
392392
dt_tz - ts
393393
msg = "can't subtract offset-naive and offset-aware datetimes"
394394
with pytest.raises(TypeError, match=msg):
395395
dt_tz - dt
396-
msg = "Timestamp subtraction must have the same timezones or no timezones"
397-
with pytest.raises(TypeError, match=msg):
398-
dt_tz - ts_tz2
399396
msg = "can't subtract offset-naive and offset-aware datetimes"
400397
with pytest.raises(TypeError, match=msg):
401398
dt - dt_tz
402-
msg = "Timestamp subtraction must have the same timezones or no timezones"
399+
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects."
403400
with pytest.raises(TypeError, match=msg):
404401
ts - dt_tz
405402
with pytest.raises(TypeError, match=msg):
406403
ts_tz2 - ts
407404
with pytest.raises(TypeError, match=msg):
408405
ts_tz2 - dt
409-
with pytest.raises(TypeError, match=msg):
410-
ts_tz - ts_tz2
411406

407+
msg = "Cannot subtract tz-naive and tz-aware"
412408
# with dti
413409
with pytest.raises(TypeError, match=msg):
414410
dti - ts_tz
415411
with pytest.raises(TypeError, match=msg):
416412
dti_tz - ts
417-
with pytest.raises(TypeError, match=msg):
418-
dti_tz - ts_tz2
419413

420414
result = dti_tz - dt_tz
421415
expected = TimedeltaIndex(["0 days", "1 days", "2 days"])

pandas/tests/scalar/timestamp/test_arithmetic.py

+33-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from datetime import (
22
datetime,
33
timedelta,
4+
timezone,
45
)
56

67
import numpy as np
@@ -99,7 +100,7 @@ def test_rsub_dtscalars(self, tz_naive_fixture):
99100
if tz_naive_fixture is None:
100101
assert other.to_datetime64() - ts == td
101102
else:
102-
msg = "subtraction must have"
103+
msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
103104
with pytest.raises(TypeError, match=msg):
104105
other.to_datetime64() - ts
105106

@@ -109,6 +110,37 @@ def test_timestamp_sub_datetime(self):
109110
assert (ts - dt).days == 1
110111
assert (dt - ts).days == -1
111112

113+
def test_subtract_tzaware_datetime(self):
114+
t1 = Timestamp("2020-10-22T22:00:00+00:00")
115+
t2 = datetime(2020, 10, 22, 22, tzinfo=timezone.utc)
116+
117+
result = t1 - t2
118+
119+
assert isinstance(result, Timedelta)
120+
assert result == Timedelta("0 days")
121+
122+
def test_subtract_timestamp_from_different_timezone(self):
123+
t1 = Timestamp("20130101").tz_localize("US/Eastern")
124+
t2 = Timestamp("20130101").tz_localize("CET")
125+
126+
result = t1 - t2
127+
128+
assert isinstance(result, Timedelta)
129+
assert result == Timedelta("0 days 06:00:00")
130+
131+
def test_subtracting_involving_datetime_with_different_tz(self):
132+
t1 = datetime(2013, 1, 1, tzinfo=timezone(timedelta(hours=-5)))
133+
t2 = Timestamp("20130101").tz_localize("CET")
134+
135+
result = t1 - t2
136+
137+
assert isinstance(result, Timedelta)
138+
assert result == Timedelta("0 days 06:00:00")
139+
140+
result = t2 - t1
141+
assert isinstance(result, Timedelta)
142+
assert result == Timedelta("-1 days +18:00:00")
143+
112144
def test_addition_subtraction_types(self):
113145
# Assert on the types resulting from Timestamp +/- various date/time
114146
# objects

pandas/tests/series/methods/test_shift.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,11 @@ def test_shift(self, datetime_series):
110110
exp = Series(TimedeltaIndex(["NaT"] + ["1 days"] * 4), name="foo")
111111
tm.assert_series_equal(result, exp)
112112

113-
# incompat tz
113+
# mismatched timezone
114114
s2 = Series(date_range("2000-01-01 09:00:00", periods=5, tz="CET"), name="foo")
115-
msg = "DatetimeArray subtraction must have the same timezones or no timezones"
116-
with pytest.raises(TypeError, match=msg):
117-
s - s2
115+
exp = Series(TimedeltaIndex(["6 hours"] * 5), name="foo")
116+
result = s - s2
117+
tm.assert_series_equal(result, exp)
118118

119119
def test_shift2(self):
120120
ts = Series(

0 commit comments

Comments
 (0)