Skip to content

Commit 33a66d6

Browse files
authored
Fix handling of abbreviated units like msec (#3998)
* Fix handling of abbreviated units like msec By default, xarray tries to decode times with pandas and falls back to cftime. This fixes the exception handler to fallback properly in the cases an unhandled abbreviated unit is passed in. * Add what's new entry
1 parent 6ca3bd7 commit 33a66d6

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@ Bug fixes
8282
- Fix bug causing :py:meth:`DataArray.interpolate_na` to always drop attributes,
8383
and added `keep_attrs` argument. (:issue:`3968`)
8484
By `Tom Nicholas <https://github.com/TomNicholas>`_.
85-
85+
- Fix bug in time parsing failing to fall back to cftime. This was causing time
86+
variables with a time unit of `'msecs'` to fail to parse. (:pull:`3998`)
87+
By `Ryan May <https://github.com/dopplershift>`_.
8688

8789
Documentation
8890
~~~~~~~~~~~~~

xarray/coding/times.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def decode_cf_datetime(num_dates, units, calendar=None, use_cftime=None):
155155
if use_cftime is None:
156156
try:
157157
dates = _decode_datetime_with_pandas(flat_num_dates, units, calendar)
158-
except (OutOfBoundsDatetime, OverflowError):
158+
except (KeyError, OutOfBoundsDatetime, OverflowError):
159159
dates = _decode_datetime_with_cftime(
160160
flat_num_dates.astype(np.float), units, calendar
161161
)

xarray/tests/test_coding_times.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,18 @@ def test_decode_360_day_calendar():
432432
assert_array_equal(actual, expected)
433433

434434

435+
@requires_cftime
436+
def test_decode_abbreviation():
437+
"""Test making sure we properly fall back to cftime on abbreviated units."""
438+
import cftime
439+
440+
val = np.array([1586628000000.0])
441+
units = "msecs since 1970-01-01T00:00:00Z"
442+
actual = coding.times.decode_cf_datetime(val, units)
443+
expected = coding.times.cftime_to_nptime(cftime.num2date(val, units))
444+
assert_array_equal(actual, expected)
445+
446+
435447
@arm_xfail
436448
@requires_cftime
437449
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)