Skip to content

Commit 5712eab

Browse files
committed
BUG #31793 subtract datetime from Timestamp
1 parent 7f910b5 commit 5712eab

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

pandas/_libs/tslibs/timestamps.pyx

+7-3
Original file line numberDiff line numberDiff line change
@@ -368,9 +368,13 @@ cdef class _Timestamp(ABCTimestamp):
368368
self = type(other)(self)
369369

370370
# validate tz's
371-
if not tz_compare(self.tzinfo, other.tzinfo):
372-
raise TypeError("Timestamp subtraction must have the "
373-
"same timezones or no timezones")
371+
naive_timezones = [
372+
el.tzinfo is None or el.tzinfo.utcoffset(el) is None
373+
for el in (self, other)
374+
]
375+
if any(naive_timezones) and not all(naive_timezones):
376+
raise TypeError("Cannot compute time difference between"
377+
" timezone-aware and naive datetime values.")
374378

375379
# scalar Timestamp/datetime - Timestamp/datetime -> yields a
376380
# Timedelta

pandas/tests/tslibs/test_timedeltas.py

+39-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds
55

6-
from pandas import Timedelta, offsets
6+
from pandas import Timedelta, offsets, Timestamp
77

88

99
@pytest.mark.parametrize(
@@ -34,3 +34,41 @@ def test_huge_nanoseconds_overflow():
3434
# GH 32402
3535
assert delta_to_nanoseconds(Timedelta(1e10)) == 1e10
3636
assert delta_to_nanoseconds(Timedelta(nanoseconds=1e10)) == 1e10
37+
38+
39+
class TestComputingDeltasWithTimezoneDifferences:
40+
def test_fails_to_subtract_when_one_date_is_naive(self):
41+
time1 = Timestamp("2020-10-28 22:08:00-04:00")
42+
time2 = Timestamp("2020-10-28 22:08:00")
43+
44+
msg = (
45+
"Cannot compute time difference between "
46+
"timezone-aware and naive datetime values."
47+
)
48+
with pytest.raises(TypeError, match=msg):
49+
time1 - time2
50+
51+
with pytest.raises(TypeError, match=msg):
52+
time2 - time1
53+
54+
def test_subtracts_dates_of_different_timezones(self):
55+
time1 = Timestamp("2020-10-28 22:08:00-04:00")
56+
time2 = Timestamp("2020-10-28 22:08:00-00:00")
57+
58+
assert time1 - time2 == Timedelta("0 days 04:00:00")
59+
60+
def test_subtracts_dates_of_different_types(self):
61+
""" Github issue 31793 """
62+
63+
time1 = Timestamp("2020-10-28 22:08:00-04:00")
64+
time2 = Timestamp("2020-10-28 22:08:00-00:00").to_pydatetime()
65+
66+
assert time1 - time2 == Timedelta("0 days 04:00:00")
67+
assert time2 - time1 == Timedelta("-1 days +20:00:00")
68+
69+
def test_subtracts_dates_that_are_both_naive(self):
70+
time1 = Timestamp("2020-10-28 22:08:00")
71+
time2 = Timestamp("2020-10-28 22:29:00")
72+
73+
assert time1 - time2 == Timedelta("-21 minutes")
74+
assert time2 - time1 == Timedelta("21 minutes")

0 commit comments

Comments
 (0)