Skip to content

Some minor changes to try and help with cftime dates #9

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
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
6 changes: 2 additions & 4 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
from .coordinates import (
DatasetCoordinates, LevelCoordinatesSource,
assert_coordinate_consistent, remap_label_indexers)
from .duck_array_ops import datetime_to_numeric
from .indexes import Indexes, default_indexes
from .merge import (
dataset_merge_method, dataset_update_method, merge_data_and_coords,
Expand Down Expand Up @@ -3854,15 +3853,14 @@ def differentiate(self, coord, edge_order=1, datetime_unit=None):
datetime_unit, _ = np.datetime_data(coord_var.dtype)
elif datetime_unit is None:
datetime_unit = 's' # Default to seconds for cftime objects
coord_var = datetime_to_numeric(
coord_var, datetime_unit=datetime_unit)
coord_var = coord_var._to_numeric(datetime_unit=datetime_unit)

variables = OrderedDict()
for k, v in self.variables.items():
if (k in self.data_vars and dim in v.dims and
k not in self.coords):
if _contains_datetime_like_objects(v):
v = datetime_to_numeric(v, datetime_unit=datetime_unit)
v = v._to_numeric(datetime_unit=datetime_unit)
grad = duck_array_ops.gradient(
v.data, coord_var, edge_order=edge_order,
axis=v.get_axis_num(dim))
Expand Down
10 changes: 5 additions & 5 deletions xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import numpy as np
import pandas as pd

from . import dask_array_ops, dtypes, npcompat, nputils, utils
from . import dask_array_ops, dtypes, npcompat, nputils
from .nputils import nanfirst, nanlast
from .pycompat import dask_array_type

Expand Down Expand Up @@ -300,16 +300,16 @@ def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float):
offset = array.min()
array = array - offset

if datetime_unit:
array = array / np.timedelta64(1, datetime_unit)

if not hasattr(array, 'dtype'): # scalar is converted to 0d-array
array = np.array(array)

if array.dtype.kind in 'O':
# possibly convert object array containing datetime.datetime
# possibly convert object array containing datetime.timedelta
array = np.asarray(pd.Series(array.ravel())).reshape(array.shape)

if datetime_unit:
array = array / np.timedelta64(1, datetime_unit)

# convert np.NaT to np.nan
if array.dtype.kind in 'mM':
return np.where(isnull(array), np.nan, array.astype(dtype))
Expand Down
48 changes: 22 additions & 26 deletions xarray/tests/test_duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,43 +575,39 @@ def test_docs():


def test_datetime_to_numeric_datetime64():
times = pd.date_range('2000', periods=5, freq='7D')
da = DataArray(times, coords=[times], dims=['time'])
result = duck_array_ops.datetime_to_numeric(da, datetime_unit='h')
expected = 24 * DataArray(np.arange(0, 35, 7), coords=da.coords)
assert_identical(result, expected)
times = pd.date_range('2000', periods=5, freq='7D').values
result = duck_array_ops.datetime_to_numeric(times, datetime_unit='h')
expected = 24 * np.arange(0, 35, 7)
np.testing.assert_array_equal(result, expected)

offset = da.isel(time=1)
offset = times[1]
result = duck_array_ops.datetime_to_numeric(
da, offset=offset, datetime_unit='h')
expected = 24 * DataArray(np.arange(-7, 28, 7), coords=da.coords)
assert_identical(result, expected)
times, offset=offset, datetime_unit='h')
expected = 24 * np.arange(-7, 28, 7)
np.testing.assert_array_equal(result, expected)

dtype = np.float32
result = duck_array_ops.datetime_to_numeric(
da, datetime_unit='h', dtype=dtype)
expected = 24 * DataArray(
np.arange(0, 35, 7), coords=da.coords).astype(dtype)
assert_identical(result, expected)
times, datetime_unit='h', dtype=dtype)
expected = 24 * np.arange(0, 35, 7).astype(dtype)
np.testing.assert_array_equal(result, expected)


@requires_cftime
def test_datetime_to_numeric_cftime():
times = cftime_range('2000', periods=5, freq='7D')
da = DataArray(times, coords=[times], dims=['time'])
result = duck_array_ops.datetime_to_numeric(da, datetime_unit='h')
expected = 24 * DataArray(np.arange(0, 35, 7), coords=da.coords)
assert_identical(result, expected)
times = cftime_range('2000', periods=5, freq='7D').values
result = duck_array_ops.datetime_to_numeric(times, datetime_unit='h')
expected = 24 * np.arange(0, 35, 7)
np.testing.assert_array_equal(result, expected)

offset = da.isel(time=1)
offset = times[1]
result = duck_array_ops.datetime_to_numeric(
da, offset=offset, datetime_unit='h')
expected = 24 * DataArray(np.arange(-7, 28, 7), coords=da.coords)
assert_identical(result, expected)
times, offset=offset, datetime_unit='h')
expected = 24 * np.arange(-7, 28, 7)
np.testing.assert_array_equal(result, expected)

dtype = np.float32
result = duck_array_ops.datetime_to_numeric(
da, datetime_unit='h', dtype=dtype)
expected = 24 * DataArray(
np.arange(0, 35, 7), coords=da.coords).astype(dtype)
assert_identical(result, expected)
times, datetime_unit='h', dtype=dtype)
expected = 24 * np.arange(0, 35, 7).astype(dtype)
np.testing.assert_array_equal(result, expected)