Skip to content

Commit d8ccc7a

Browse files
authored
Fix precision drop when indexing a datetime64 arrays. (#1942)
* Fix precision drop when indexing a datetime64 arrays. * minor style fix. * Add a link to github issue in numpy/numpy
1 parent 519ff80 commit d8ccc7a

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ Enhancements
4141
Bug fixes
4242
~~~~~~~~~
4343

44+
- Fix the precision drop after indexing datetime64 arrays (:issue:`1932`).
45+
By `Keisuke Fujii <https://github.com/fujiisoup>`_.
46+
4447
.. _whats-new.0.10.1:
4548

4649
v0.10.1 (25 February 2018)

xarray/core/indexing.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -911,6 +911,10 @@ def __getitem__(self, indexer):
911911
result = np.datetime64('NaT', 'ns')
912912
elif isinstance(result, timedelta):
913913
result = np.timedelta64(getattr(result, 'value', result), 'ns')
914+
elif isinstance(result, pd.Timestamp):
915+
# Work around for GH: pydata/xarray#1932 and numpy/numpy#10668
916+
# numpy fails to convert pd.Timestamp to np.datetime64[ns]
917+
result = np.asarray(result.to_datetime64())
914918
elif self.dtype != object:
915919
result = np.asarray(result, dtype=self.dtype)
916920

xarray/tests/test_variable.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1719,6 +1719,13 @@ def test_coordinate_alias(self):
17191719
x = Coordinate('x', [1, 2, 3])
17201720
assert isinstance(x, IndexVariable)
17211721

1722+
def test_datetime64(self):
1723+
# GH:1932 Make sure indexing keeps precision
1724+
t = np.array([1518418799999986560, 1518418799999996560],
1725+
dtype='datetime64[ns]')
1726+
v = IndexVariable('t', t)
1727+
assert v[0].data == t[0]
1728+
17221729
# These tests make use of multi-dimensional variables, which are not valid
17231730
# IndexVariable objects:
17241731
@pytest.mark.xfail

0 commit comments

Comments
 (0)