From 7e6261a67ae4de398ae7138ab74ce84a8016180f Mon Sep 17 00:00:00 2001 From: MeeseeksMachine <39504233+meeseeksmachine@users.noreply.github.com> Date: Wed, 12 Apr 2023 01:11:55 +0200 Subject: [PATCH] Backport PR #52555 on branch 2.0.x (BUG: DatetimeArray.unit when constructed from a non-nano ndarray) (#52608) Backport PR #52555: BUG: DatetimeArray.unit when constructed from a non-nano ndarray Co-authored-by: Luke Manley --- doc/source/whatsnew/v2.0.1.rst | 1 + pandas/core/arrays/datetimelike.py | 5 ++++- pandas/tests/arrays/datetimes/test_constructors.py | 7 +++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v2.0.1.rst b/doc/source/whatsnew/v2.0.1.rst index 7b4dc890da3e1..a98c162c37d74 100644 --- a/doc/source/whatsnew/v2.0.1.rst +++ b/doc/source/whatsnew/v2.0.1.rst @@ -30,6 +30,7 @@ Bug fixes - Bug in :func:`pandas.testing.assert_series_equal` where ``check_dtype=False`` would still raise for datetime or timedelta types with different resolutions (:issue:`52449`) - Bug in :meth:`ArrowDtype.__from_arrow__` not respecting if dtype is explicitly given (:issue:`52533`) - Bug in :func:`read_csv` casting PyArrow datetimes to NumPy when ``dtype_backend="pyarrow"`` and ``parse_dates`` is set causing a performance bottleneck in the process (:issue:`52546`) +- Bug in :class:`arrays.DatetimeArray` constructor returning an incorrect unit when passed a non-nanosecond numpy datetime array (:issue:`52555`) .. --------------------------------------------------------------------------- .. _whatsnew_201.other: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 8c647f45af530..976262a0f1573 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1826,7 +1826,10 @@ def __init__( values = values._ndarray elif dtype is None: - dtype = self._default_dtype + if isinstance(values, np.ndarray) and values.dtype.kind in "Mm": + dtype = values.dtype + else: + dtype = self._default_dtype if not isinstance(values, np.ndarray): raise ValueError( diff --git a/pandas/tests/arrays/datetimes/test_constructors.py b/pandas/tests/arrays/datetimes/test_constructors.py index 6670d07a4c075..bbc66dcd328c3 100644 --- a/pandas/tests/arrays/datetimes/test_constructors.py +++ b/pandas/tests/arrays/datetimes/test_constructors.py @@ -127,6 +127,13 @@ def test_copy(self): arr = DatetimeArray(data, copy=True) assert arr._ndarray is not data + @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) + def test_numpy_datetime_unit(self, unit): + data = np.array([1, 2, 3], dtype=f"M8[{unit}]") + arr = DatetimeArray(data) + assert arr.unit == unit + assert arr[0].unit == unit + class TestSequenceToDT64NS: def test_tz_dtype_mismatch_raises(self):