Skip to content

Commit 15eb9cb

Browse files
committed
Better error message for OOB result
Closes pandas-dev#31774
1 parent 015c1c1 commit 15eb9cb

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v1.0.2.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ Bug fixes
6464

6565
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with a tz-aware index (:issue:`26683`)
6666
- Bug where :func:`to_datetime` would raise when passed ``pd.NA`` (:issue:`32213`)
67+
- Improved error message when subtracting two :class:`Timestamp` that result in an invalide :class:`Timedelta` (:issue:`31774`)
6768

6869
**Categorical**
6970

pandas/_libs/tslibs/c_timestamp.pyx

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,15 @@ cdef class _Timestamp(datetime):
299299
# scalar Timestamp/datetime - Timestamp/datetime -> yields a
300300
# Timedelta
301301
from pandas._libs.tslibs.timedeltas import Timedelta
302+
from pandas._libs.tslibs.timestamps import Timestamp
302303
try:
303304
return Timedelta(self.value - other.value)
304-
except (OverflowError, OutOfBoundsDatetime):
305+
except (OverflowError, OutOfBoundsDatetime) as e:
306+
if isinstance(other, Timestamp):
307+
raise OverflowError(
308+
"Result is too large for pandas.Timestamp. Convert inputs "
309+
"to datetime.datetime before subtracting."
310+
) from e
305311
pass
306312
elif is_datetime64_object(self):
307313
# GH#28286 cython semantics for __rsub__, `other` is actually

pandas/tests/scalar/timestamp/test_arithmetic.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,15 @@ def test_overflow_offset_raises(self):
6060
with pytest.raises(OverflowError, match=msg):
6161
stamp - offset_overflow
6262

63+
def test_overflow_timestamp_raises(self):
64+
# https://github.com/pandas-dev/pandas/issues/31774
65+
msg = "Result is too large"
66+
a = Timestamp("2101-01-01 00:00:00")
67+
b = Timestamp("1688-01-01 00:00:00")
68+
69+
with pytest.raises(OverflowError, match=msg):
70+
a - b
71+
6372
def test_delta_preserve_nanos(self):
6473
val = Timestamp(1337299200000000123)
6574
result = val + timedelta(1)

0 commit comments

Comments
 (0)