xarray icon indicating copy to clipboard operation
xarray copied to clipboard

combine_by_coords fails when aligning axes containing time zone information

Open mgunyho opened this issue 8 months ago • 9 comments

What happened?

I was trying to combine two data arrays with misaligned coordinates using xr.combine_by_coords(..., join="outer"). One of the coordinates has datetime objects with time zone information in it. However, in this case, combine_by_coords crashes with TypeError: Cannot interpret 'datetime64[us, UTC]' as a data type.

What did you expect to happen?

The data arrays should be combined successfully.

Minimal Complete Verifiable Example

# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "xarray[complete]@git+https://github.com/pydata/xarray.git@main",
#   "pytz>=2026.1.post1",
# ]
# ///

import datetime
import pytz
import xarray as xr


arrs = []

for i in range(2):
    # leaving out the .astimezone(...) works
    t = datetime.datetime(2026, 3, 1, hour=i).astimezone(pytz.timezone("UTC"))
    da = xr.DataArray().expand_dims(
        time=[t],
        dummy=[i],  # changing to dummy=[0] or leaving this out works
    )
    arrs.append(da)

xr.combine_by_coords(arrs, join="outer")

Steps to reproduce

Run the MCVE script using uv run.

MVCE confirmation

  • [x] Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • [x] Complete example — the example is self-contained, including all data and the text of any traceback.
  • [x] Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • [x] New issue — a search of GitHub Issues suggests this is not a duplicate.
  • [x] Recent environment — the issue occurs with the latest version of xarray and its dependencies.

Relevant log output

Traceback (most recent call last):
  File ".../code/misc/bug-reports/2026-03-16-xarray-combine_by_coords-timezone/main-standalone.py", line 25, in <module>
    xr.combine_by_coords(arrs, join="outer")
    ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/combine.py", line 1097, in combine_by_coords
    combined_temp_dataset = _combine_single_variable_hypercube(
        temp_datasets,
    ...<5 lines>...
        combine_attrs=combine_attrs,
    )
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/combine.py", line 775, in _combine_single_variable_hypercube
    concatenated = _combine_nd(
        combined_ids,
    ...<6 lines>...
        combine_attrs=combine_attrs,
    )
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/combine.py", line 262, in _combine_nd
    combined_ids = _combine_all_along_first_dim(
        combined_ids,
    ...<6 lines>...
        combine_attrs=combine_attrs,
    )
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/combine.py", line 294, in _combine_all_along_first_dim
    new_combined_ids[new_id] = _combine_1d(
                               ~~~~~~~~~~~^
        datasets,
        ^^^^^^^^^
    ...<6 lines>...
        combine_attrs=combine_attrs,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/combine.py", line 324, in _combine_1d
    combined = concat(
        datasets,
    ...<6 lines>...
        combine_attrs=combine_attrs,
    )
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/concat.py", line 325, in concat
    return _dataset_concat(
        objs,
    ...<8 lines>...
        create_index_for_new_dim=create_index_for_new_dim,
    )
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/concat.py", line 645, in _dataset_concat
    align(
    ~~~~~^
        *datasets, join=join, copy=False, exclude=[dim_name], fill_value=fill_value
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/alignment.py", line 967, in align
    aligner.align()
    ~~~~~~~~~~~~~^^
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/alignment.py", line 659, in align
    self.align_indexes()
    ~~~~~~~~~~~~~~~~~~^^
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/structure/alignment.py", line 485, in align_indexes
    joined_index = joiner(matching_indexes)
  File ".../.cache/uv/environments-v2/main-standalone-c4d81dcd74734a38/lib/python3.13/site-packages/xarray/core/indexes.py", line 907, in join
    coord_dtype = np.result_type(self.coord_dtype, other.coord_dtype)
TypeError: Cannot interpret 'datetime64[us, UTC]' as a data type

Anything else we need to know?

If there is no time zone information (i.e. no .astimezone(...) in the MVCE), the crash doesn't occur. If the join is one-dimensional (i.e. the dummy coordinate is equal or left out in the MVCE), the crash doesn't occur.

Environment

INSTALLED VERSIONS

commit: None python: 3.13.5 (main, Jun 12 2025, 12:40:22) [Clang 20.1.4 ] python-bits: 64 OS: Linux OS-release: 6.18.16-100.fc42.x86_64 machine: x86_64 processor: byteorder: little LC_ALL: None LANG: en_US.UTF-8 LOCALE: ('en_US', 'UTF-8') libhdf5: 1.14.6 libnetcdf: 4.9.3

xarray: 2026.2.1.dev23+g885e8d111 pandas: 3.0.1 numpy: 2.4.3 scipy: 1.17.1 netCDF4: 1.7.4 pydap: 3.5.9 h5netcdf: 1.8.1 h5py: 3.16.0 zarr: 3.1.5 cftime: 1.6.5 nc_time_axis: 1.4.1 iris: None bottleneck: 1.6.0 dask: 2026.1.2 distributed: 2026.1.2 matplotlib: 3.10.8 cartopy: 0.25.0 seaborn: 0.13.2 numbagg: 0.9.4 fsspec: 2026.2.0 cupy: None pint: None sparse: 0.18.0 flox: 0.11.2 numpy_groupies: 0.11.3 setuptools: None pip: None conda: None pytest: None mypy: None IPython: None sphinx: None

mgunyho avatar Mar 16 '26 10:03 mgunyho

Hey! I may be able to help with this bug.

I build custom fixes for Python projects and automation systems.

If you'd like help resolving this issue quickly feel free to reach out.

Happy to take a look 👍

FocusMode-coder avatar Mar 16 '26 10:03 FocusMode-coder

Probably the same issue, but there is also an exception when combining datasets with variables that have disjoint coordinates:

arrs = []

for i in range(2):
    t = datetime.datetime(2026, 3, 1, hour=i).astimezone(pytz.timezone("UTC"))
    da = xr.DataArray().expand_dims(
        time=[t],
    )
    var = ["foo", "bar"][i]
    ds = xr.Dataset({var: da})
    arrs.append(ds)

xr.combine_by_coords(arrs, join="outer")
# -> TypeError: Cannot interpret 'datetime64[us, UTC]' as a data type

mgunyho avatar Mar 17 '26 02:03 mgunyho

Thanks for taking the time to write this up @mgunyho. It looks like a bug having to do with the handling of pandas.arrays.DatetimeArray (which is the type of da.time.data once the DataArray is constructed).

@ilan-gold I tried to dig through the code and figure out what the intention is for this case, but I can't quite tell.

jsignell avatar Mar 17 '26 19:03 jsignell

We shouldn't be hanging on to timezone in .data. I fail to understand how this keep happening!

Alternatively, maybe we should just bite the bullet and get timezones working with pandas' DatetimeArray

dcherian avatar Mar 17 '26 19:03 dcherian

I am happy to fix :) Should have something posted by tomorrow!

ilan-gold avatar Mar 17 '26 20:03 ilan-gold

We shouldn't be hanging on to timezone in .data. I fail to understand how this keep happening!

Why not?

ilan-gold avatar Mar 18 '26 10:03 ilan-gold

Is DatetimeArray an allowed type already? I didn't think so but haven't followed closely in a while.

dcherian avatar Mar 18 '26 13:03 dcherian

Is DatetimeArray an allowed type already? I didn't think so but haven't followed closely in a while.

We disallowed it on incoming pandas.DataFrame objects a while back to preserve some baked-in behavior that used to exist in xarray. I asked in the PR description of doing that what was going on there, but didn't follow up to try to find out.

But otherwise, it's allowed i.e., you are allowed to construct an xarray object directly using them. Otherwise I think a lot of the datetime preservation for coords would probably start failing (a guess).

ilan-gold avatar Mar 18 '26 13:03 ilan-gold

Hi. We don't know if this is related, but we are observing similar problems starting with xarray 2025.1.2. Any suggestion how to improve is much welcome.

  • https://github.com/daq-tools/kotori/issues/271

amotl avatar May 15 '26 13:05 amotl