Skip to content

Commit a87602e

Browse files
committed
Merge branch 'main' into keep-attrs
2 parents f776190 + ba2e831 commit a87602e

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,9 @@ Bug fixes
115115

116116
- Fix the ``align_chunks`` parameter on the :py:meth:`~xarray.Dataset.to_zarr` method, it was not being
117117
passed to the underlying :py:meth:`~xarray.backends.api` method (:issue:`10501`, :pull:`10516`).
118+
- Fix error when encoding an empty :py:class:`numpy.datetime64` array
119+
(:issue:`10722`, :pull:`10723`). By `Spencer Clark
120+
<https://github.com/spencerkclark>`_.
118121

119122
Documentation
120123
~~~~~~~~~~~~~

xarray/coding/times.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,9 +1065,12 @@ def _eagerly_encode_cf_datetime(
10651065
# parse with cftime instead
10661066
raise OutOfBoundsDatetime
10671067
assert np.issubdtype(dates.dtype, "datetime64")
1068-
if calendar in ["standard", "gregorian"] and np.nanmin(dates).astype(
1069-
"=M8[us]"
1070-
).astype(datetime) < datetime(1582, 10, 15):
1068+
if (
1069+
calendar in ["standard", "gregorian"]
1070+
and dates.size > 0
1071+
and np.nanmin(dates).astype("=M8[us]").astype(datetime)
1072+
< datetime(1582, 10, 15)
1073+
):
10711074
raise_gregorian_proleptic_gregorian_mismatch_error = True
10721075

10731076
time_unit, ref_date = _unpack_time_unit_and_ref_date(units)

xarray/tests/test_coding_times.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2198,3 +2198,24 @@ def test_roundtrip_0size_timedelta(time_unit: PDDatetimeUnitOptions) -> None:
21982198
decoded.load()
21992199
assert decoded.dtype == np.dtype("=m8[s]")
22002200
assert decoded.encoding == encoding
2201+
2202+
2203+
def test_roundtrip_empty_datetime64_array(time_unit: PDDatetimeUnitOptions) -> None:
2204+
# Regression test for GitHub issue #10722.
2205+
encoding = {
2206+
"units": "days since 1990-1-1",
2207+
"dtype": np.dtype("float64"),
2208+
"calendar": "standard",
2209+
}
2210+
times = date_range("2000", periods=0, unit=time_unit)
2211+
variable = Variable(["time"], times, encoding=encoding)
2212+
2213+
encoded = conventions.encode_cf_variable(variable, name="foo")
2214+
assert encoded.dtype == np.dtype("float64")
2215+
2216+
decode_times = CFDatetimeCoder(time_unit=time_unit)
2217+
roundtripped = conventions.decode_cf_variable(
2218+
"foo", encoded, decode_times=decode_times
2219+
)
2220+
assert_identical(variable, roundtripped)
2221+
assert roundtripped.dtype == variable.dtype

0 commit comments

Comments
 (0)