Skip to content

Commit 7e6261a

Browse files
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 <[email protected]>
1 parent 99bcfe3 commit 7e6261a

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/source/whatsnew/v2.0.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Bug fixes
3030
- 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`)
3131
- Bug in :meth:`ArrowDtype.__from_arrow__` not respecting if dtype is explicitly given (:issue:`52533`)
3232
- 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`)
33+
- Bug in :class:`arrays.DatetimeArray` constructor returning an incorrect unit when passed a non-nanosecond numpy datetime array (:issue:`52555`)
3334

3435
.. ---------------------------------------------------------------------------
3536
.. _whatsnew_201.other:

pandas/core/arrays/datetimelike.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1826,7 +1826,10 @@ def __init__(
18261826
values = values._ndarray
18271827

18281828
elif dtype is None:
1829-
dtype = self._default_dtype
1829+
if isinstance(values, np.ndarray) and values.dtype.kind in "Mm":
1830+
dtype = values.dtype
1831+
else:
1832+
dtype = self._default_dtype
18301833

18311834
if not isinstance(values, np.ndarray):
18321835
raise ValueError(

pandas/tests/arrays/datetimes/test_constructors.py

+7
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,13 @@ def test_copy(self):
127127
arr = DatetimeArray(data, copy=True)
128128
assert arr._ndarray is not data
129129

130+
@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
131+
def test_numpy_datetime_unit(self, unit):
132+
data = np.array([1, 2, 3], dtype=f"M8[{unit}]")
133+
arr = DatetimeArray(data)
134+
assert arr.unit == unit
135+
assert arr[0].unit == unit
136+
130137

131138
class TestSequenceToDT64NS:
132139
def test_tz_dtype_mismatch_raises(self):

0 commit comments

Comments
 (0)