Skip to content

Commit b6fa495

Browse files
committed
BUG: handle overflow for large nanosecond timedeltas
1 parent 1797ba5 commit b6fa495

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

pandas/_libs/tslibs/timedeltas.pyx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,12 @@ cdef int64_t _numeric_to_td64ns(
300300
if is_integer_object(item) and item == NPY_NAT:
301301
return NPY_NAT
302302

303+
# Early overflow guard for scalar numeric input
304+
if unit=="ns" and is_integer_object(item):
305+
if item>9223372036854775807 or item <-9223372036854775808:
306+
raise OutOfBoundsTimedelta(
307+
f"Cannot cast {item} from {unit} to 'ns' without overflow."
308+
)
303309
try:
304310
ival = cast_from_unit(item, unit, out_reso)
305311
except OutOfBoundsDatetime as err:

pandas/tests/scalar/timedelta/test_constructors.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import numpy as np
55
import pytest
6-
6+
import pandas as pd
77
from pandas._libs.tslibs import OutOfBoundsTimedelta
88
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
99
from pandas.errors import Pandas4Warning
@@ -778,3 +778,7 @@ def test_parsed_unit():
778778
# 7 digits after the decimal
779779
td = Timedelta("1 Day 2:03:04.0123450")
780780
assert td.unit == "ns"
781+
def test_to_timedelta_overflow_raises():
782+
msg = "Cannot cast .* from ns to 'ns' without overflow"
783+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
784+
pd.to_timedelta(10**20, unit="ns")

0 commit comments

Comments
 (0)