Skip to content

Commit 46591d2

Browse files
Modify _encode_datetime_with_cftime for compatibility with cftime > 1.4.0 (#4871)
1 parent c83dfd1 commit 46591d2

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ Bug fixes
9696
:py:meth:`Dataset.to_zarr` (:issue:`4783`, :pull:`4795`).
9797
By `Julien Seguinot <https://github.com/juseg>`_.
9898
- Add :py:meth:`Dataset.drop_isel` and :py:meth:`DataArray.drop_isel` (:issue:`4658`, :pull:`4819`). By `Daniel Mesejo <https://github.com/mesejo>`_.
99+
- Fix time encoding bug associated with using cftime versions greater than
100+
1.4.0 with xarray (:issue:`4870`, :pull:`4871`). By `Spencer Clark <https://github.com/spencerkclark>`_.
99101

100102
Documentation
101103
~~~~~~~~~~~~~

xarray/coding/times.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ def _encode_datetime_with_cftime(dates, units, calendar):
391391
def encode_datetime(d):
392392
return np.nan if d is None else cftime.date2num(d, units, calendar)
393393

394-
return np.vectorize(encode_datetime)(dates)
394+
return np.array([encode_datetime(d) for d in dates.ravel()]).reshape(dates.shape)
395395

396396

397397
def cast_to_int_if_safe(num):

xarray/tests/test_coding_times.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from xarray import DataArray, Dataset, Variable, coding, conventions, decode_cf
1010
from xarray.coding.times import (
11+
_encode_datetime_with_cftime,
1112
cftime_to_nptime,
1213
decode_cf_datetime,
1314
encode_cf_datetime,
@@ -995,3 +996,18 @@ def test_encode_decode_roundtrip(freq):
995996
encoded = conventions.encode_cf_variable(variable)
996997
decoded = conventions.decode_cf_variable("time", encoded)
997998
assert_equal(variable, decoded)
999+
1000+
1001+
@requires_cftime
1002+
def test__encode_datetime_with_cftime():
1003+
# See GH 4870. cftime versions > 1.4.0 required us to adapt the
1004+
# way _encode_datetime_with_cftime was written.
1005+
import cftime
1006+
1007+
calendar = "gregorian"
1008+
times = cftime.num2date([0, 1], "hours since 2000-01-01", calendar)
1009+
1010+
encoding_units = "days since 2000-01-01"
1011+
expected = cftime.date2num(times, encoding_units, calendar)
1012+
result = _encode_datetime_with_cftime(times, encoding_units, calendar)
1013+
np.testing.assert_equal(result, expected)

0 commit comments

Comments
 (0)