Skip to content
forked from pydata/xarray

Commit

Permalink
promote floating-point numeric datetimes to 64-bit before decoding (p…
Browse files Browse the repository at this point in the history
…ydata#9182)

* promote floating-point dates to 64-bit while decoding

* add a test to make sure we don't regress

* whats-new entry
  • Loading branch information
keewis authored Jun 28, 2024
1 parent f4183ec commit 42ed6d3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Bug fixes
~~~~~~~~~
- Make :py:func:`testing.assert_allclose` work with numpy 2.0 (:issue:`9165`, :pull:`9166`).
By `Pontus Lurcock <https://github.com/pont-us>`_.
- Promote floating-point numeric datetimes before decoding (:issue:`9179`, :pull:`9182`).
By `Justus Magin <https://github.com/keewis>`_.


Documentation
Expand Down
2 changes: 2 additions & 0 deletions xarray/coding/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,8 @@ def _decode_datetime_with_pandas(
# timedelta64 value, and therefore would raise an error in the lines above.
if flat_num_dates.dtype.kind in "iu":
flat_num_dates = flat_num_dates.astype(np.int64)
elif flat_num_dates.dtype.kind in "f":
flat_num_dates = flat_num_dates.astype(np.float64)

# Cast input ordinals to integers of nanoseconds because pd.to_timedelta
# works much faster when dealing with integers (GH 1399).
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 @@ -1182,6 +1182,22 @@ def test_decode_0size_datetime(use_cftime):
np.testing.assert_equal(expected, actual)


def test_decode_float_datetime():
num_dates = np.array([1867128, 1867134, 1867140], dtype="float32")
units = "hours since 1800-01-01"
calendar = "standard"

expected = np.array(
["2013-01-01T00:00:00", "2013-01-01T06:00:00", "2013-01-01T12:00:00"],
dtype="datetime64[ns]",
)

actual = decode_cf_datetime(
num_dates, units=units, calendar=calendar, use_cftime=False
)
np.testing.assert_equal(actual, expected)


@requires_cftime
def test_scalar_unit() -> None:
# test that a scalar units (often NaN when using to_netcdf) does not raise an error
Expand Down

0 comments on commit 42ed6d3

Please sign in to comment.