Skip to content

Fix precision drop when indexing a datetime64 arrays. #1942

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 3 commits into from
Feb 27, 2018
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
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ Enhancements
Bug fixes
~~~~~~~~~

- Fix the precision drop after indexing datetime64 arrays (:issue:`1932`).
By `Keisuke Fujii <https://github.com/fujiisoup>`_.

.. _whats-new.0.10.1:

v0.10.1 (25 February 2018)
Expand Down
4 changes: 4 additions & 0 deletions xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,10 @@ def __getitem__(self, indexer):
result = np.datetime64('NaT', 'ns')
elif isinstance(result, timedelta):
result = np.timedelta64(getattr(result, 'value', result), 'ns')
elif isinstance(result, pd.Timestamp):
# Work around for GH: pydata/xarray#1932 and numpy/numpy#10668
# numpy fails to convert pd.Timestamp to np.datetime64[ns]
result = np.asarray(result.to_datetime64())
elif self.dtype != object:
result = np.asarray(result, dtype=self.dtype)

Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -1719,6 +1719,13 @@ def test_coordinate_alias(self):
x = Coordinate('x', [1, 2, 3])
assert isinstance(x, IndexVariable)

def test_datetime64(self):
# GH:1932 Make sure indexing keeps precision
t = np.array([1518418799999986560, 1518418799999996560],
dtype='datetime64[ns]')
v = IndexVariable('t', t)
assert v[0].data == t[0]

# These tests make use of multi-dimensional variables, which are not valid
# IndexVariable objects:
@pytest.mark.xfail
Expand Down