Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,12 @@ cdef int64_t _numeric_to_td64ns(
if is_integer_object(item) and item == NPY_NAT:
return NPY_NAT

# Early overflow guard for scalar numeric input
if unit=="ns" and is_integer_object(item):
if item>9223372036854775807 or item <-9223372036854775808:
raise OutOfBoundsTimedelta(
f"Cannot cast {item} from {unit} to 'ns' without overflow."
)
try:
ival = cast_from_unit(item, unit, out_reso)
except OutOfBoundsDatetime as err:
Expand Down
6 changes: 5 additions & 1 deletion pandas/tests/scalar/timedelta/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import numpy as np
import pytest

import pandas as pd
from pandas._libs.tslibs import OutOfBoundsTimedelta
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
from pandas.errors import Pandas4Warning
Expand Down Expand Up @@ -778,3 +778,7 @@ def test_parsed_unit():
# 7 digits after the decimal
td = Timedelta("1 Day 2:03:04.0123450")
assert td.unit == "ns"
def test_to_timedelta_overflow_raises():
msg = "Cannot cast .* from ns to 'ns' without overflow"
with pytest.raises(OutOfBoundsTimedelta, match=msg):
pd.to_timedelta(10**20, unit="ns")