diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index b8e2b1fafe326..f9c6465cd948e 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -370,9 +370,9 @@ def _wrap_results(result, dtype: np.dtype, fill_value=None): result = np.nan if isna(result): - result = np.datetime64("NaT", "ns") + result = np.datetime64("NaT", "ns").astype(dtype) else: - result = np.int64(result).view("datetime64[ns]") + result = np.int64(result).view(dtype) # retain original unit result = result.astype(dtype, copy=False) else: diff --git a/pandas/tests/arrays/datetimes/test_reductions.py b/pandas/tests/arrays/datetimes/test_reductions.py index d0553f9608f25..59a4443ac9e19 100644 --- a/pandas/tests/arrays/datetimes/test_reductions.py +++ b/pandas/tests/arrays/datetimes/test_reductions.py @@ -10,6 +10,10 @@ class TestReductions: + @pytest.fixture(params=["s", "ms", "us", "ns"]) + def unit(self, request): + return request.param + @pytest.fixture def arr1d(self, tz_naive_fixture): """Fixture returning DatetimeArray with parametrized timezones""" @@ -28,17 +32,20 @@ def arr1d(self, tz_naive_fixture): ) return arr - def test_min_max(self, arr1d): + def test_min_max(self, arr1d, unit): arr = arr1d + arr = arr.as_unit(unit) tz = arr.tz result = arr.min() - expected = pd.Timestamp("2000-01-02", tz=tz) + expected = pd.Timestamp("2000-01-02", tz=tz).as_unit(unit) assert result == expected + assert result.unit == expected.unit result = arr.max() - expected = pd.Timestamp("2000-01-05", tz=tz) + expected = pd.Timestamp("2000-01-05", tz=tz).as_unit(unit) assert result == expected + assert result.unit == expected.unit result = arr.min(skipna=False) assert result is NaT diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index ae8791a774ed5..d6deafb9012ff 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -1157,10 +1157,14 @@ def prng(self): class TestDatetime64NaNOps: + @pytest.fixture(params=["s", "ms", "us", "ns"]) + def unit(self, request): + return request.param + # Enabling mean changes the behavior of DataFrame.mean # See https://github.com/pandas-dev/pandas/issues/24752 - def test_nanmean(self): - dti = pd.date_range("2016-01-01", periods=3) + def test_nanmean(self, unit): + dti = pd.date_range("2016-01-01", periods=3).as_unit(unit) expected = dti[1] for obj in [dti, DatetimeArray(dti), Series(dti)]: @@ -1173,8 +1177,9 @@ def test_nanmean(self): result = nanops.nanmean(obj) assert result == expected - @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) - def test_nanmean_skipna_false(self, dtype): + @pytest.mark.parametrize("constructor", ["M8", "m8"]) + def test_nanmean_skipna_false(self, constructor, unit): + dtype = f"{constructor}[{unit}]" arr = np.arange(12).astype(np.int64).view(dtype).reshape(4, 3) arr[-1, -1] = "NaT"