Skip to content

Commit 06d2266

Browse files
committed
BUG: cannot subtract Timestamp with different timezones (pandas-dev#31793)
1 parent 9f6a91a commit 06d2266

File tree

7 files changed

+89
-35
lines changed

7 files changed

+89
-35
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,7 @@ Timezones
936936
^^^^^^^^^
937937
- Bug in different ``tzinfo`` objects representing UTC not being treated as equivalent (:issue:`39216`)
938938
- Bug in ``dateutil.tz.gettz("UTC")`` not being recognized as equivalent to other UTC-representing tzinfos (:issue:`39276`)
939+
- Bug in ``Timestamp`` and ``DatetimeIndex`` incorrectly raising a ``TypeError`` when subtracting two times that don't have the same timezone offset (:issue:`31793`)
939940

940941
Numeric
941942
^^^^^^^

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 compare 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

+2-11
Original file line numberDiff line numberDiff line change
@@ -708,12 +708,7 @@ def _sub_datetime_arraylike(self, other):
708708
assert is_datetime64_dtype(other)
709709
other = type(self)(other)
710710

711-
if not self._has_same_tz(other):
712-
# require tz compat
713-
raise TypeError(
714-
f"{type(self).__name__} subtraction must have the same "
715-
"timezones or no timezones"
716-
)
711+
self._assert_tzawareness_compat(other)
717712

718713
self_i8 = self.asi8
719714
other_i8 = other.asi8
@@ -759,11 +754,7 @@ def _sub_datetimelike_scalar(self, other):
759754
if other is NaT: # type: ignore[comparison-overlap]
760755
return self - NaT
761756

762-
if not self._has_same_tz(other):
763-
# require tz compat
764-
raise TypeError(
765-
"Timestamp subtraction must have the same timezones or no timezones"
766-
)
757+
self._assert_tzawareness_compat(other)
767758

768759
i8 = self.asi8
769760
result = checked_add_with_arr(i8, -other.value, arr_mask=self._isnan)

pandas/tests/arithmetic/test_datetime64.py

+42-6
Original file line numberDiff line numberDiff line change
@@ -864,6 +864,46 @@ def test_dt64arr_isub_timedeltalike_scalar(
864864
rng -= two_hours
865865
tm.assert_equal(rng, expected)
866866

867+
def test_dt64_array_sub_dt_with_different_timezone(self, box_with_array):
868+
t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
869+
t1 = tm.box_expected(t1, box_with_array)
870+
t2 = Timestamp("20130101").tz_localize("CET")
871+
872+
result = t1 - t2
873+
expected = TimedeltaIndex(
874+
["0 days 06:00:00", "1 days 06:00:00", "2 days 06:00:00"]
875+
)
876+
expected = tm.box_expected(expected, box_with_array)
877+
tm.assert_equal(result, expected)
878+
879+
result = t2 - t1
880+
expected = TimedeltaIndex(
881+
["-1 days +18:00:00", "-2 days +18:00:00", "-3 days +18:00:00"]
882+
)
883+
expected = tm.box_expected(expected, box_with_array)
884+
tm.assert_equal(result, expected)
885+
886+
def test_dt64_array_sub_dt64_array_with_different_timezone(self, box_with_array):
887+
t1 = date_range("20130101", periods=3).tz_localize("US/Eastern")
888+
t1 = tm.box_expected(t1, box_with_array)
889+
890+
t2 = date_range("20130101", periods=3).tz_localize("CET")
891+
t2 = tm.box_expected(t2, box_with_array)
892+
893+
result = t1 - t2
894+
expected = TimedeltaIndex(
895+
["0 days 06:00:00", "0 days 06:00:00", "0 days 06:00:00"]
896+
)
897+
expected = tm.box_expected(expected, box_with_array)
898+
tm.assert_equal(result, expected)
899+
900+
result = t2 - t1
901+
expected = TimedeltaIndex(
902+
["-1 days +18:00:00", "-1 days +18:00:00", "-1 days +18:00:00"]
903+
)
904+
expected = tm.box_expected(expected, box_with_array)
905+
tm.assert_equal(result, expected)
906+
867907
# TODO: redundant with test_dt64arr_add_timedeltalike_scalar
868908
def test_dt64arr_add_td64_scalar(self, box_with_array):
869909
# scalar timedeltas/np.timedelta64 objects
@@ -1045,7 +1085,7 @@ def test_dt64arr_aware_sub_dt64ndarray_raises(
10451085
dt64vals = dti.values
10461086

10471087
dtarr = tm.box_expected(dti, box_with_array)
1048-
msg = "subtraction must have the same timezones or"
1088+
msg = "Cannot compare tz-naive and tz-aware datetime"
10491089
with pytest.raises(TypeError, match=msg):
10501090
dtarr - dt64vals
10511091
with pytest.raises(TypeError, match=msg):
@@ -2235,24 +2275,20 @@ def test_sub_dti_dti(self):
22352275

22362276
dti = date_range("20130101", periods=3)
22372277
dti_tz = date_range("20130101", periods=3).tz_localize("US/Eastern")
2238-
dti_tz2 = date_range("20130101", periods=3).tz_localize("UTC")
22392278
expected = TimedeltaIndex([0, 0, 0])
22402279

22412280
result = dti - dti
22422281
tm.assert_index_equal(result, expected)
22432282

22442283
result = dti_tz - dti_tz
22452284
tm.assert_index_equal(result, expected)
2246-
msg = "DatetimeArray subtraction must have the same timezones or"
2285+
msg = "Cannot compare tz-naive and tz-aware datetime-like objects"
22472286
with pytest.raises(TypeError, match=msg):
22482287
dti_tz - dti
22492288

22502289
with pytest.raises(TypeError, match=msg):
22512290
dti - dti_tz
22522291

2253-
with pytest.raises(TypeError, match=msg):
2254-
dti_tz - dti_tz2
2255-
22562292
# isub
22572293
dti -= dti
22582294
tm.assert_index_equal(dti, expected)

pandas/tests/arithmetic/test_timedelta64.py

+4-9
Original file line numberDiff line numberDiff line change
@@ -384,36 +384,31 @@ def _check(result, expected):
384384
expected = Timedelta("0 days")
385385
_check(result, expected)
386386

387+
# gotta chedk this
387388
# tz mismatches
388-
msg = "Timestamp subtraction must have the same timezones or no timezones"
389+
msg = "Cannot compare tz-naive and tz-aware datetime-like objects."
389390
with pytest.raises(TypeError, match=msg):
390391
dt_tz - ts
391392
msg = "can't subtract offset-naive and offset-aware datetimes"
392393
with pytest.raises(TypeError, match=msg):
393394
dt_tz - dt
394-
msg = "Timestamp subtraction must have the same timezones or no timezones"
395-
with pytest.raises(TypeError, match=msg):
396-
dt_tz - ts_tz2
397395
msg = "can't subtract offset-naive and offset-aware datetimes"
398396
with pytest.raises(TypeError, match=msg):
399397
dt - dt_tz
400-
msg = "Timestamp subtraction must have the same timezones or no timezones"
398+
msg = "Cannot compare tz-naive and tz-aware datetime-like objects."
401399
with pytest.raises(TypeError, match=msg):
402400
ts - dt_tz
403401
with pytest.raises(TypeError, match=msg):
404402
ts_tz2 - ts
405403
with pytest.raises(TypeError, match=msg):
406404
ts_tz2 - dt
407-
with pytest.raises(TypeError, match=msg):
408-
ts_tz - ts_tz2
409405

406+
msg = "Cannot compare tz-naive and tz-aware"
410407
# with dti
411408
with pytest.raises(TypeError, match=msg):
412409
dti - ts_tz
413410
with pytest.raises(TypeError, match=msg):
414411
dti_tz - ts
415-
with pytest.raises(TypeError, match=msg):
416-
dti_tz - ts_tz2
417412

418413
result = dti_tz - dt_tz
419414
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 compare 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

+3-4
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,10 @@ 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
118117

119118
def test_shift2(self):
120119
ts = Series(

0 commit comments

Comments
 (0)