Repository: pydata/xarray

Issue:
Difference in time coordinate values in xarray tutorial dataset loaded with numpy v2 
### What happened?

Time coordinate values are significantly different (second precision) if numpy v2 in the environment for the xarray "air temperature" tutorial dataset. This leads to discrepancies and errors in selection by date strings.

Numpy v2.0.0
```
array(['2013-01-01T00:02:06.757437440', '2013-01-01T05:59:27.234179072',
       '2013-01-01T11:56:47.710920704', ...,
       '2014-12-31T05:58:10.831327232', '2014-12-31T11:55:31.308068864',
       '2014-12-31T18:02:01.540624384'], dtype='datetime64[ns]')
```

Numpy v1.26.4
```
array(['2013-01-01T00:00:00.000000000', '2013-01-01T06:00:00.000000000',
       '2013-01-01T12:00:00.000000000', ...,
       '2014-12-31T06:00:00.000000000', '2014-12-31T12:00:00.000000000',
       '2014-12-31T18:00:00.000000000'], dtype='datetime64[ns]')
```

### What did you expect to happen?

I expect time coordinates to be identical for different numpy versions

### Minimal Complete Verifiable Example

```Python
#mamba create -n xarray2024.6.0 xarray ipython pooch netCDF4 numpy>2
import xarray as xr
ds = xr.tutorial.load_dataset("air_temperature")
print(ds.time.values)
dates = ['2013-07-09', '2013-10-11', '2013-12-24']
ds.sel(time=dates)
```


### MVCE confirmation

- [X] Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
- [X] Complete example — the example is self-contained, including all data and the text of any traceback.
- [X] Verifiable example — the example copy & pastes into an IPython prompt or [Binder notebook](https://mybinder.org/v2/gh/pydata/xarray/main?urlpath=lab/tree/doc/examples/blank_template.ipynb), returning the result.
- [X] New issue — a search of GitHub Issues suggests this is not a duplicate.
- [X] Recent environment — the issue occurs with the latest version of xarray and its dependencies.

### Relevant log output

```Python
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[21], line 2
      1 dates = ['2013-07-09', '2013-10-11', '2013-12-24']
----> 2 ds.sel(time=dates)

File ~/miniforge3/envs/xarray2024.6.0/lib/python3.12/site-packages/xarray/core/dataset.py:3126, in Dataset.sel(self, indexers, method, tolerance, drop, **indexers_kwargs)
   3058 """Returns a new dataset with each array indexed by tick labels
   3059 along the specified dimension(s).
   3060 
   (...)
   3123 
   3124 """
   3125 indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "sel")
-> 3126 query_results = map_index_queries(
   3127     self, indexers=indexers, method=method, tolerance=tolerance
   3128 )
   3130 if drop:
   3131     no_scalar_variables = {}

File ~/miniforge3/envs/xarray2024.6.0/lib/python3.12/site-packages/xarray/core/indexing.py:192, in map_index_queries(obj, indexers, method, tolerance, **indexers_kwargs)
    190         results.append(IndexSelResult(labels))
    191     else:
--> 192         results.append(index.sel(labels, **options))
    194 merged = merge_sel_results(results)
    196 # drop dimension coordinates found in dimension indexers
    197 # (also drop multi-index if any)
    198 # (.sel() already ensures alignment)

File ~/miniforge3/envs/xarray2024.6.0/lib/python3.12/site-packages/xarray/core/indexes.py:801, in PandasIndex.sel(self, labels, method, tolerance)
    799     indexer = get_indexer_nd(self.index, label_array, method, tolerance)
    800     if np.any(indexer < 0):
--> 801         raise KeyError(f"not all values found in index {coord_name!r}")
    803 # attach dimension names and/or coordinates to positional indexer
    804 if isinstance(label, Variable):

KeyError: "not all values found in index 'time'"
```


### Anything else we need to know?

https://github.com/xarray-contrib/xarray-tutorial/issues/271

### Environment

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.12.4 | packaged by conda-forge | (main, Jun 17 2024, 10:13:44) [Clang 16.0.6 ]
python-bits: 64
OS: Darwin
OS-release: 23.5.0
machine: arm64
processor: arm
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: ('en_US', 'UTF-8')
libhdf5: 1.14.3
libnetcdf: 4.9.2

xarray: 2024.6.0
pandas: 2.2.2
numpy: 2.0.0
scipy: None
netCDF4: 1.7.1
pydap: None
h5netcdf: None
h5py: None
zarr: None
cftime: 1.6.4
nc_time_axis: None
iris: None
bottleneck: None
dask: None
distributed: None
matplotlib: None
cartopy: None
seaborn: None
numbagg: None
fsspec: None
cupy: None
pint: None
sparse: None
flox: None
numpy_groupies: None
setuptools: 70.1.1
pip: 24.0
conda: None
pytest: None
mypy: None
IPython: 8.25.0
sphinx: None

</details>


Discussion:

Patch:
diff --git a/ci/requirements/all-but-dask.yml b/ci/requirements/all-but-dask.yml
index 2f47643c..abf6a886 100644
--- a/ci/requirements/all-but-dask.yml
+++ b/ci/requirements/all-but-dask.yml
@@ -22,12 +22,12 @@ dependencies:
   - netcdf4
   - numba
   - numbagg
-  - numpy
+  - numpy<2
   - packaging
   - pandas
   - pint>=0.22
   - pip
-  - pydap
+  # - pydap
   - pytest
   - pytest-cov
   - pytest-env
diff --git a/ci/requirements/environment-windows.yml b/ci/requirements/environment-windows.yml
index 4cdddc67..2eedc9b0 100644
--- a/ci/requirements/environment-windows.yml
+++ b/ci/requirements/environment-windows.yml
@@ -29,7 +29,7 @@ dependencies:
   # - pint>=0.22
   - pip
   - pre-commit
-  - pydap
+  # - pydap
   - pytest
   - pytest-cov
   - pytest-env
diff --git a/ci/requirements/environment.yml b/ci/requirements/environment.yml
index f1a10bc0..317e1fe5 100644
--- a/ci/requirements/environment.yml
+++ b/ci/requirements/environment.yml
@@ -35,7 +35,7 @@ dependencies:
   - pooch
   - pre-commit
   - pyarrow # pandas raises a deprecation warning without this, breaking doctests
-  - pydap
+  # - pydap
   - pytest
   - pytest-cov
   - pytest-env
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index 97631b4c..c58f73cb 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -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
diff --git a/xarray/coding/times.py b/xarray/coding/times.py
index 466e847e..34d4f9a2 100644
--- a/xarray/coding/times.py
+++ b/xarray/coding/times.py
@@ -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).


Test patch:
diff --git a/xarray/tests/test_coding_times.py b/xarray/tests/test_coding_times.py
index 09221d66..393f8400 100644
--- a/xarray/tests/test_coding_times.py
+++ b/xarray/tests/test_coding_times.py
@@ -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