Skip to content

Commit 9df2dfc

Browse files
Set longdouble=False in cftime.date2num within the date encoding context (#7171)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent ab726c5 commit 9df2dfc

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

doc/whats-new.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@ Internal Changes
5959
By `Maximilian Roos <https://github.com/max-sixty>`_.
6060

6161

62+
- Explicitly specify ``longdouble=False`` in :py:func:`cftime.date2num` when
63+
encoding times to preserve existing behavior and prevent future errors when it
64+
is eventually set to ``True`` by default in cftime (:pull:`7171`). By
65+
`Spencer Clark <https://github.com/spencerkclark>`_.
6266

6367
.. _whats-new.2022.10.0:
6468

xarray/coding/times.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,18 @@ def _encode_datetime_with_cftime(dates, units, calendar):
581581
dates = dates.astype("M8[us]").astype(datetime)
582582

583583
def encode_datetime(d):
584-
return np.nan if d is None else cftime.date2num(d, units, calendar)
584+
# Since netCDF files do not support storing float128 values, we ensure
585+
# that float64 values are used by setting longdouble=False in num2date.
586+
# This try except logic can be removed when xarray's minimum version of
587+
# cftime is at least 1.6.2.
588+
try:
589+
return (
590+
np.nan
591+
if d is None
592+
else cftime.date2num(d, units, calendar, longdouble=False)
593+
)
594+
except TypeError:
595+
return np.nan if d is None else cftime.date2num(d, units, calendar)
585596

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

xarray/tests/test_coding_times.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1080,7 +1080,14 @@ def test__encode_datetime_with_cftime() -> None:
10801080
times = cftime.num2date([0, 1], "hours since 2000-01-01", calendar)
10811081

10821082
encoding_units = "days since 2000-01-01"
1083-
expected = cftime.date2num(times, encoding_units, calendar)
1083+
# Since netCDF files do not support storing float128 values, we ensure that
1084+
# float64 values are used by setting longdouble=False in num2date. This try
1085+
# except logic can be removed when xarray's minimum version of cftime is at
1086+
# least 1.6.2.
1087+
try:
1088+
expected = cftime.date2num(times, encoding_units, calendar, longdouble=False)
1089+
except TypeError:
1090+
expected = cftime.date2num(times, encoding_units, calendar)
10841091
result = _encode_datetime_with_cftime(times, encoding_units, calendar)
10851092
np.testing.assert_equal(result, expected)
10861093

0 commit comments

Comments
 (0)