Skip to content

Raise error for invalid reference date for encoding time units #5288

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

Merged
merged 4 commits into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -27,6 +27,8 @@ New Features
- :py:meth:`Dataset.interp` now allows interpolation with non-numerical datatypes,
such as booleans, instead of dropping them. (:issue:`4761` :pull:`5008`).
By `Jimmy Westling <https://github.com/illviljan>`_.
- Raise more informative error when decoding time variables with invalid reference dates.
(:issue:`5199`, :pull:`5288`). By `Giacomo Caria <https://github.com/gcaria>`_.

Breaking changes
~~~~~~~~~~~~~~~~
Expand Down
2 changes: 2 additions & 0 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ def _ensure_padded_year(ref_date):
# No four-digit strings, assume the first digits are the year and pad
# appropriately
matches_start_digits = re.match(r"(\d+)(.*)", ref_date)
if not matches_start_digits:
raise ValueError(f"invalid reference date for time units: {ref_date}")
ref_year, everything_else = [s for s in matches_start_digits.groups()]
ref_date_padded = "{:04d}{}".format(int(ref_year), everything_else)

Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_coding_times.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,12 @@ def test_encode_cf_datetime_overflow(shape):
roundtrip = decode_cf_datetime(num, units, calendar)
np.testing.assert_array_equal(dates, roundtrip)

with pytest.raises(ValueError, match="invalid time units"):
encode_cf_datetime(dates, units="days after 2000-01-01")

with pytest.raises(ValueError, match="invalid reference date"):
encode_cf_datetime(dates, units="days since NO_YEAR")


def test_encode_cf_datetime_pandas_min():
# GH 2623
Expand Down