Skip to content

Commit 3a6d4cd

Browse files
authored
BUG: to_datetime with xarray DataArray and specifie unit errors (#44074)
1 parent f2abbd9 commit 3a6d4cd

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,7 @@ Conversion
470470
^^^^^^^^^^
471471
- 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`)
472472
- Bug in :class:`Series` constructor returning 0 for missing values with dtype ``int64`` and ``False`` for dtype ``bool`` (:issue:`43017`, :issue:`43018`)
473+
- Bug in :func:`to_datetime` with ``arg:xr.DataArray`` and ``unit="ns"`` specified raises TypeError (:issue:`44053`)
473474
-
474475

475476
Strings

pandas/core/tools/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,6 @@ def _convert_listlike_datetimes(
325325
-------
326326
Index-like of parsed dates
327327
"""
328-
329328
if isinstance(arg, (list, tuple)):
330329
arg = np.array(arg, dtype="O")
331330

@@ -525,6 +524,7 @@ def _to_datetime_with_unit(arg, unit, name, tz, errors: str) -> Index:
525524
arr = arg.astype(f"datetime64[{unit}]")
526525
tz_parsed = None
527526
else:
527+
arg = np.asarray(arg)
528528
arr, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors)
529529

530530
if errors == "ignore":

pandas/tests/tools/test_to_datetime.py

+19
Original file line numberDiff line numberDiff line change
@@ -2640,6 +2640,25 @@ def test_empty_string_datetime_coerce__unit():
26402640
tm.assert_index_equal(expected, result)
26412641

26422642

2643+
@td.skip_if_no("xarray")
2644+
def test_xarray_coerce_unit():
2645+
# GH44053
2646+
import xarray as xr
2647+
2648+
arr = xr.DataArray([1, 2, 3])
2649+
result = to_datetime(arr, unit="ns")
2650+
expected = DatetimeIndex(
2651+
[
2652+
"1970-01-01 00:00:00.000000001",
2653+
"1970-01-01 00:00:00.000000002",
2654+
"1970-01-01 00:00:00.000000003",
2655+
],
2656+
dtype="datetime64[ns]",
2657+
freq=None,
2658+
)
2659+
tm.assert_index_equal(result, expected)
2660+
2661+
26432662
@pytest.mark.parametrize("cache", [True, False])
26442663
def test_to_datetime_monotonic_increasing_index(cache):
26452664
# GH28238

0 commit comments

Comments
 (0)