Skip to content

BUG: Raise OutOfBoundsDatetime in DataFrame.replace when value exceeds datetime64[ns] bounds (GH#61671) #61717

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,7 @@ Datetimelike
- Bug in :func:`tseries.frequencies.to_offset` would fail to parse frequency strings starting with "LWOM" (:issue:`59218`)
- Bug in :meth:`DataFrame.fillna` raising an ``AssertionError`` instead of ``OutOfBoundsDatetime`` when filling a ``datetime64[ns]`` column with an out-of-bounds timestamp. Now correctly raises ``OutOfBoundsDatetime``. (:issue:`61208`)
- Bug in :meth:`DataFrame.min` and :meth:`DataFrame.max` casting ``datetime64`` and ``timedelta64`` columns to ``float64`` and losing precision (:issue:`60850`)
- Bug in :meth:`DataFrame.replace` where attempting to replace a ``datetime64[ns]`` column with an out-of-bounds timestamp would raise an ``AssertionError`` or silently coerce. Now correctly raises ``OutOfBoundsDatetime``. (:issue:`61671`)
- Bug in :meth:`Dataframe.agg` with df with missing values resulting in IndexError (:issue:`58810`)
- Bug in :meth:`DatetimeIndex.is_year_start` and :meth:`DatetimeIndex.is_quarter_start` does not raise on Custom business days frequencies bigger then "1C" (:issue:`58664`)
- Bug in :meth:`DatetimeIndex.is_year_start` and :meth:`DatetimeIndex.is_quarter_start` returning ``False`` on double-digit frequencies (:issue:`58523`)
Expand Down
19 changes: 19 additions & 0 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
ensure_str,
is_bool,
is_complex,
is_datetime64_dtype,
is_float,
is_integer,
is_object_dtype,
Expand Down Expand Up @@ -1358,6 +1359,24 @@ def find_result_type(left_dtype: DtypeObj, right: Any) -> DtypeObj:
dtype, _ = infer_dtype_from(right)
new_dtype = find_common_type([left_dtype, dtype])

# special case: datetime64[ns] inferred but the value may be out of bounds
if (
is_datetime64_dtype(new_dtype)
and lib.is_scalar(right)
and isinstance(right, (np.datetime64, dt.datetime, Timestamp))
):
try:
ts = Timestamp(right)
casted = np.datetime64(ts, "ns")
if Timestamp(casted) != ts:
raise OutOfBoundsDatetime(
f"{right!r} overflows datetime64[ns] during dtype inference"
)
except (OverflowError, ValueError) as e:
raise OutOfBoundsDatetime(
f"Cannot safely store {right!r} in inferred dtype 'datetime64[ns]'"
) from e

return new_dtype


Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/methods/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,18 @@ def test_replace_with_nil_na(self):
result = ser.replace("nil", "anything else")
tm.assert_frame_equal(expected, result)

def test_replace_outofbounds_datetime_raises(self):
# GH 61671
df = DataFrame([np.nan], dtype="datetime64[ns]")
too_big = datetime(3000, 1, 1)
from pandas.errors import OutOfBoundsDatetime

with pytest.raises(
OutOfBoundsDatetime,
match="Cannot safely store .* in inferred dtype 'datetime64\\[ns\\]'",
):
df.replace(np.nan, too_big)


class TestDataFrameReplaceRegex:
@pytest.mark.parametrize(
Expand Down
Loading