Skip to content
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

BUG: setitem with mixed-resolution dt64s #56419

Merged
merged 14 commits into from
Apr 23, 2024
Merged
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 @@ -360,6 +360,7 @@ Datetimelike
- Bug in :func:`date_range` where the last valid timestamp would sometimes not be produced (:issue:`56134`)
- Bug in :func:`date_range` where using a negative frequency value would not include all points between the start and end values (:issue:`56382`)
- Bug in :func:`tseries.api.guess_datetime_format` would fail to infer time format when "%Y" == "%H%M" (:issue:`57452`)
- Bug in setting scalar values with mismatched resolution into arrays with non-nanosecond ``datetime64``, ``timedelta64`` or :class:`DatetimeTZDtype` incorrectly truncating those scalars (:issue:`56410`)

Timedelta
^^^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ def _unbox_scalar(self, value) -> np.datetime64:
if value is NaT:
return np.datetime64(value._value, self.unit)
else:
return value.as_unit(self.unit).asm8
return value.as_unit(self.unit, round_ok=False).asm8

def _scalar_from_string(self, value) -> Timestamp | NaTType:
return Timestamp(value, tz=self.tz)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ def _unbox_scalar(self, value) -> np.timedelta64:
if value is NaT:
return np.timedelta64(value._value, self.unit)
else:
return value.as_unit(self.unit).asm8
return value.as_unit(self.unit, round_ok=False).asm8

def _scalar_from_string(self, value) -> Timedelta | NaTType:
return Timedelta(value)
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,8 @@ def _parsed_string_to_bounds(
freq = OFFSET_TO_PERIOD_FREQSTR.get(reso.attr_abbrev, reso.attr_abbrev)
per = Period(parsed, freq=freq)
start, end = per.start_time, per.end_time
start = start.as_unit(self.unit)
end = end.as_unit(self.unit)

# GH 24076
# If an incoming date string contained a UTC offset, need to localize
Expand Down
17 changes: 15 additions & 2 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
Shape,
npt,
)
from pandas.errors import AbstractMethodError
from pandas.errors import (
AbstractMethodError,
OutOfBoundsDatetime,
)
from pandas.util._decorators import cache_readonly
from pandas.util._exceptions import find_stack_level
from pandas.util._validators import validate_bool_kwarg
Expand Down Expand Up @@ -478,7 +481,17 @@ def coerce_to_target_dtype(self, other, warn_on_upcast: bool = False) -> Block:
f"{self.values.dtype}. Please report a bug at "
"https://github.com/pandas-dev/pandas/issues."
)
return self.astype(new_dtype)
try:
return self.astype(new_dtype)
except OutOfBoundsDatetime as err:
# e.g. GH#56419 if self.dtype is a low-resolution dt64 and we try to
# upcast to a higher-resolution dt64, we may have entries that are
# out of bounds for the higher resolution.
# Re-raise with a more informative message.
raise OutOfBoundsDatetime(
f"Incompatible (high-resolution) value for dtype='{self.dtype}'. "
"Explicitly cast before operating."
) from err

@final
def convert(self) -> list[Block]:
Expand Down
33 changes: 33 additions & 0 deletions pandas/tests/series/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,39 @@ def test_slice_key(self, obj, key, expected, warn, val, indexer_sli, is_inplace)
raise AssertionError("xfail not relevant for this test.")


@pytest.mark.parametrize(
"exp_dtype",
[
"M8[ms]",
"M8[ms, UTC]",
"m8[ms]",
],
)
class TestCoercionDatetime64HigherReso(CoercionTest):
@pytest.fixture
def obj(self, exp_dtype):
idx = date_range("2011-01-01", freq="D", periods=4, unit="s")
if exp_dtype == "m8[ms]":
idx = idx - Timestamp("1970-01-01")
assert idx.dtype == "m8[s]"
elif exp_dtype == "M8[ms, UTC]":
idx = idx.tz_localize("UTC")
return Series(idx)

@pytest.fixture
def val(self, exp_dtype):
ts = Timestamp("2011-01-02 03:04:05.678").as_unit("ms")
if exp_dtype == "m8[ms]":
return ts - Timestamp("1970-01-01")
elif exp_dtype == "M8[ms, UTC]":
return ts.tz_localize("UTC")
return ts

@pytest.fixture
def warn(self):
return FutureWarning


@pytest.mark.parametrize(
"val,exp_dtype,warn",
[
Expand Down
28 changes: 24 additions & 4 deletions pandas/tests/series/methods/test_clip.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import numpy as np
import pytest

from pandas.errors import OutOfBoundsDatetime

import pandas as pd
from pandas import (
Series,
Expand Down Expand Up @@ -131,12 +133,30 @@ def test_clip_with_datetimes(self):
)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("dtype", [object, "M8[us]"])
def test_clip_with_timestamps_and_oob_datetimes(self, dtype):
def test_clip_with_timestamps_and_oob_datetimes_object(self):
# GH-42794
ser = Series([datetime(1, 1, 1), datetime(9999, 9, 9)], dtype=dtype)
ser = Series([datetime(1, 1, 1), datetime(9999, 9, 9)], dtype=object)

result = ser.clip(lower=Timestamp.min, upper=Timestamp.max)
expected = Series([Timestamp.min, Timestamp.max], dtype=dtype)
expected = Series([Timestamp.min, Timestamp.max], dtype=object)

tm.assert_series_equal(result, expected)

def test_clip_with_timestamps_and_oob_datetimes_non_nano(self):
# GH#56410
dtype = "M8[us]"
ser = Series([datetime(1, 1, 1), datetime(9999, 9, 9)], dtype=dtype)

msg = (
r"Incompatible \(high-resolution\) value for dtype='datetime64\[us\]'. "
"Explicitly cast before operating"
)
with pytest.raises(OutOfBoundsDatetime, match=msg):
ser.clip(lower=Timestamp.min, upper=Timestamp.max)

lower = Timestamp.min.as_unit("us")
upper = Timestamp.max.as_unit("us")
result = ser.clip(lower=lower, upper=upper)
expected = Series([lower, upper], dtype=dtype)

tm.assert_series_equal(result, expected)
14 changes: 2 additions & 12 deletions pandas/tests/series/methods/test_fillna.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,12 +308,7 @@ def test_datetime64_fillna(self):
"scalar",
[
False,
pytest.param(
True,
marks=pytest.mark.xfail(
reason="GH#56410 scalar case not yet addressed"
),
),
True,
],
)
@pytest.mark.parametrize("tz", [None, "UTC"])
Expand Down Expand Up @@ -342,12 +337,7 @@ def test_datetime64_fillna_mismatched_reso_no_rounding(self, tz, scalar):
"scalar",
[
False,
pytest.param(
True,
marks=pytest.mark.xfail(
reason="GH#56410 scalar case not yet addressed"
),
),
True,
],
)
def test_timedelta64_fillna_mismatched_reso_no_rounding(self, scalar):
Expand Down
Loading