diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 0a2ac4da8e96b..af7706f624323 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -470,6 +470,7 @@ Conversion ^^^^^^^^^^ - Bug in :class:`UInt64Index` constructor when passing a list containing both positive integers small enough to cast to int64 and integers too large too hold in int64 (:issue:`42201`) - Bug in :class:`Series` constructor returning 0 for missing values with dtype ``int64`` and ``False`` for dtype ``bool`` (:issue:`43017`, :issue:`43018`) +- Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`) - Strings diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 21357f37853d9..2838c33a42716 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -325,7 +325,6 @@ def _convert_listlike_datetimes( ------- Index-like of parsed dates """ - if isinstance(arg, (list, tuple)): arg = np.array(arg, dtype="O") @@ -525,6 +524,7 @@ def _to_datetime_with_unit(arg, unit, name, tz, errors: str) -> Index: arr = arg.astype(f"datetime64[{unit}]") tz_parsed = None else: + arg = np.asarray(arg) arr, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors) if errors == "ignore": diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 850ce6df21b7f..3fa6441e47242 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -2640,6 +2640,25 @@ def test_empty_string_datetime_coerce__unit(): tm.assert_index_equal(expected, result) +@td.skip_if_no("xarray") +def test_xarray_coerce_unit(): + # GH44053 + import xarray as xr + + arr = xr.DataArray([1, 2, 3]) + result = to_datetime(arr, unit="ns") + expected = DatetimeIndex( + [ + "1970-01-01 00:00:00.000000001", + "1970-01-01 00:00:00.000000002", + "1970-01-01 00:00:00.000000003", + ], + dtype="datetime64[ns]", + freq=None, + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_monotonic_increasing_index(cache): # GH28238