Skip to content

Commit 188141f

Browse files
spencerkclarkshoyer
authored andcommitted
Fix datetime.timedelta casting bug in coding.times.infer_datetime_units (#2128)
* Fix #2127 * Fix typo in time-series.rst * Use pd.to_timedelta to convert to np.timedelta64 objects * Install cftime through netcdf4 through pip * box=False
1 parent d1b669e commit 188141f

File tree

4 files changed

+10
-4
lines changed

4 files changed

+10
-4
lines changed

ci/requirements-py27-windows.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ dependencies:
88
- h5py
99
- h5netcdf
1010
- matplotlib
11-
- netcdf4
1211
- pathlib2
1312
- pytest
1413
- flake8
@@ -21,4 +20,4 @@ dependencies:
2120
- rasterio
2221
- zarr
2322
- pip:
24-
- cftime
23+
- netcdf4

doc/time-series.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ native representation of dates to those that fall between the years 1678 and
7373
returned as arrays of ``cftime.datetime`` objects and a ``CFTimeIndex``
7474
can be used for indexing. The ``CFTimeIndex`` enables only a subset of
7575
the indexing functionality of a ``pandas.DatetimeIndex`` and is only enabled
76-
when using standalone version of ``cftime`` (not the version packaged with
76+
when using the standalone version of ``cftime`` (not the version packaged with
7777
earlier versions ``netCDF4``). See :ref:`CFTimeIndex` for more information.
7878

7979
Datetime indexing

xarray/coding/times.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,11 @@ def infer_datetime_units(dates):
253253
else:
254254
reference_date = dates[0] if len(dates) > 0 else '1970-01-01'
255255
reference_date = format_cftime_datetime(reference_date)
256-
unique_timedeltas = np.unique(np.diff(dates)).astype('timedelta64[ns]')
256+
unique_timedeltas = np.unique(np.diff(dates))
257+
if unique_timedeltas.dtype == np.dtype('O'):
258+
# Convert to np.timedelta64 objects using pandas to work around a
259+
# NumPy casting bug: https://github.com/numpy/numpy/issues/11096
260+
unique_timedeltas = pd.to_timedelta(unique_timedeltas, box=False)
257261
units = _infer_time_units_from_diff(unique_timedeltas)
258262
return '%s since %s' % (units, reference_date)
259263

xarray/tests/test_coding_times.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,9 @@ def test_infer_cftime_datetime_units():
587587
'seconds since 1900-01-01 00:00:00.000000'),
588588
([date_type(1900, 1, 1),
589589
date_type(1900, 1, 2, 0, 0, 0, 5)],
590+
'days since 1900-01-01 00:00:00.000000'),
591+
([date_type(1900, 1, 1), date_type(1900, 1, 8),
592+
date_type(1900, 1, 16)],
590593
'days since 1900-01-01 00:00:00.000000')]:
591594
assert expected == coding.times.infer_datetime_units(dates)
592595

0 commit comments

Comments
 (0)