Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify _encode_datetime_with_cftime for compatibility with cftime > 1.4.0 #4871

Merged
merged 5 commits into from
Feb 7, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ Bug fixes
:py:meth:`Dataset.to_zarr` (:issue:`4783`, :pull:`4795`).
By `Julien Seguinot <https://github.com/juseg>`_.
- Add :py:meth:`Dataset.drop_isel` and :py:meth:`DataArray.drop_isel` (:issue:`4658`, :pull:`4819`). By `Daniel Mesejo <https://github.com/mesejo>`_.
- Fix time encoding bug associated with using cftime versions greater than
1.4.0 with xarray (:issue:`4870`, :pull:`4871`). By `Spencer Clark <https://github.com/spencerkclark>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
2 changes: 1 addition & 1 deletion xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ def _encode_datetime_with_cftime(dates, units, calendar):
def encode_datetime(d):
return np.nan if d is None else cftime.date2num(d, units, calendar)

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


def cast_to_int_if_safe(num):
Expand Down
16 changes: 16 additions & 0 deletions xarray/tests/test_coding_times.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from xarray import DataArray, Dataset, Variable, coding, conventions, decode_cf
from xarray.coding.times import (
_encode_datetime_with_cftime,
cftime_to_nptime,
decode_cf_datetime,
encode_cf_datetime,
Expand Down Expand Up @@ -995,3 +996,18 @@ def test_encode_decode_roundtrip(freq):
encoded = conventions.encode_cf_variable(variable)
decoded = conventions.decode_cf_variable("time", encoded)
assert_equal(variable, decoded)


@requires_cftime
def test__encode_datetime_with_cftime():
# See GH 4870. cftime versions > 1.4.0 required us to adapt the
# way _encode_datetime_with_cftime was written.
import cftime

calendar = "gregorian"
times = cftime.num2date([0, 1], "hours since 2000-01-01", calendar)

encoding_units = "days since 2000-01-01"
expected = cftime.date2num(times, encoding_units, calendar)
result = _encode_datetime_with_cftime(times, encoding_units, calendar)
np.testing.assert_equal(result, expected)