Skip to content

Commit 5377b16

Browse files
committed
Raise TypeError for non-datetime x_new
1 parent a37ec55 commit 5377b16

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

xarray/core/dataset.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1984,11 +1984,26 @@ def maybe_variable(obj, k):
19841984
except KeyError:
19851985
return as_variable((k, range(obj.dims[k])))
19861986

1987+
def _validate_interp_indexer(x, new_x):
1988+
# In the case of datetimes, the restrictions placed on indexers
1989+
# used with interp are stronger than those which are placed on
1990+
# isel, so we need an additional check after _validate_indexers.
1991+
if (_contains_datetime_like_objects(x) and
1992+
not _contains_datetime_like_objects(new_x)):
1993+
raise TypeError('When interpolating over a datetime-like '
1994+
'coordinate, the coordinates to '
1995+
'interpolate to must be either datetime '
1996+
'strings or datetimes. '
1997+
'Instead got\n{}'.format(new_x))
1998+
else:
1999+
return (x, new_x)
2000+
19872001
variables = OrderedDict()
19882002
for name, var in iteritems(obj._variables):
19892003
if name not in indexers:
19902004
if var.dtype.kind in 'uifc':
1991-
var_indexers = {k: (maybe_variable(obj, k), v) for k, v
2005+
var_indexers = {k: _validate_interp_indexer(
2006+
maybe_variable(obj, k), v) for k, v
19922007
in indexers.items() if k in var.dims}
19932008
variables[name] = missing.interp(
19942009
var, var_indexers, method, **kwargs)

xarray/tests/test_interp.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,3 +555,21 @@ def test_cftime_single_string():
555555
expected = xr.DataArray(0.5, coords={'time': times_new_array})
556556

557557
assert_allclose(actual, expected)
558+
559+
560+
@requires_scipy
561+
def test_datetime_to_non_datetime_error():
562+
da = xr.DataArray(np.arange(24), dims='time',
563+
coords={'time': pd.date_range('2000-01-01', periods=24)})
564+
with pytest.raises(TypeError):
565+
da.interp(time=0.5)
566+
567+
568+
@requires_cftime
569+
@requires_scipy
570+
def test_cftime_to_non_cftime_error():
571+
times = xr.cftime_range('2000', periods=24, freq='D')
572+
da = xr.DataArray(np.arange(24), coords=[times], dims='time')
573+
574+
with pytest.raises(TypeError):
575+
da.interp(time=0.5)

0 commit comments

Comments
 (0)