Repository: pydata/xarray

Issue:
Not able to slice dataset using its own coordinate value
#### Code Sample, a copy-pastable example if possible

```python
In [1]: import xarray as xr
In [2]: ds = xr.open_dataset('test.nc')
In [3]: ds.sel(time=ds.time[0]) #works
In [4]: ds.sel(time=ds.time[1], method='nearest') #works
In [5]: ds.sel(time=ds.time[1]) #does not work
```

```python
In [6]: ds.time[0]
Out[6]: 
<xarray.DataArray 'time' ()>
array('2018-02-12T06:00:00.000000000', dtype='datetime64[ns]')
Coordinates:
    time     datetime64[ns] 2018-02-12T06:00:00
    site     float64 ...
Attributes:
    standard_name:  time

In [7]: ds.time[1]
Out[7]: 
<xarray.DataArray 'time' ()>
array('2018-02-12T06:59:59.999986000', dtype='datetime64[ns]')
Coordinates:
    time     datetime64[ns] 2018-02-12T06:59:59.999986
    site     float64 ...
Attributes:
    standard_name:  time
```

#### Problem description

xarray sometimes fails to slice using its own coordinate values. It looks like it may have to do with precision. Traceback below, test file attached.

```python
In [7]: ds.sel(time=ds.time[1])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-7-371d2f896b4a> in <module>()
----> 1 ds.sel(time=ds.time[1])

/usr/lib/python2.7/site-packages/xarray/core/dataset.pyc in sel(self, method, tolerance, drop, **indexers)
   1444 
   1445         pos_indexers, new_indexes = indexing.remap_label_indexers(
-> 1446             self, v_indexers, method=method, tolerance=tolerance
   1447         )
   1448         # attach indexer's coordinate to pos_indexers

/usr/lib/python2.7/site-packages/xarray/core/indexing.pyc in remap_label_indexers(data_obj, indexers, method, tolerance)
    234         else:
    235             idxr, new_idx = convert_label_indexer(index, label,
--> 236                                                   dim, method, tolerance)
    237             pos_indexers[dim] = idxr
    238             if new_idx is not None:

/usr/lib/python2.7/site-packages/xarray/core/indexing.pyc in convert_label_indexer(index, label, index_name, method, tolerance)
    163                 indexer, new_index = index.get_loc_level(label.item(), level=0)
    164             else:
--> 165                 indexer = get_loc(index, label.item(), method, tolerance)
    166         elif label.dtype.kind == 'b':
    167             indexer = label

/usr/lib/python2.7/site-packages/xarray/core/indexing.pyc in get_loc(index, label, method, tolerance)
     93 def get_loc(index, label, method=None, tolerance=None):
     94     kwargs = _index_method_kwargs(method, tolerance)
---> 95     return index.get_loc(label, **kwargs)
     96 
     97 

/usr/lib/python2.7/site-packages/pandas/core/indexes/datetimes.pyc in get_loc(self, key, method, tolerance)
   1444                 return Index.get_loc(self, stamp, method, tolerance)
   1445             except KeyError:
-> 1446                 raise KeyError(key)
   1447             except ValueError as e:
   1448                 # list-like tolerance size must match target index size

KeyError: 1518418799999986000L
```

#### Expected Output

#### Output of ``xr.show_versions()``

<details>

```python
In [9]: xr.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.14.final.0
python-bits: 64
OS: Linux
OS-release: 4.14.15-1-ARCH
machine: x86_64
processor: 
byteorder: little
LC_ALL: None
LANG: en_NZ.UTF-8
LOCALE: en_NZ.UTF-8

xarray: 0.10.0
pandas: 0.22.0
numpy: 1.14.0
scipy: 0.17.1
netCDF4: 1.2.9
h5netcdf: None
Nio: None
bottleneck: None
cyordereddict: None
dask: 0.11.1
matplotlib: 2.1.0
cartopy: 0.14.2
seaborn: None
setuptools: 34.2.0
pip: 9.0.1
conda: None
pytest: 3.3.1
IPython: 5.2.2
sphinx: None
```
[test.zip](https://github.com/pydata/xarray/files/1742872/test.zip)



</details>


Discussion:

Patch:
diff --git a/README.rst b/README.rst
index 37061e2c..69ca0201 100644
--- a/README.rst
+++ b/README.rst
@@ -7,6 +7,8 @@ xarray: N-D labeled arrays and datasets
    :target: https://ci.appveyor.com/project/shoyer/xray
 .. image:: https://coveralls.io/repos/pydata/xarray/badge.svg
    :target: https://coveralls.io/r/pydata/xarray
+.. image:: https://readthedocs.org/projects/xray/badge/?version=latent
+   :target: http://xarray.pydata.org/
 .. image:: https://img.shields.io/pypi/v/xarray.svg
    :target: https://pypi.python.org/pypi/xarray/
 .. image:: https://zenodo.org/badge/13221727.svg
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index 89c4323d..8b200103 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -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)
diff --git a/xarray/core/indexing.py b/xarray/core/indexing.py
index e902aa8f..49ae0c5b 100644
--- a/xarray/core/indexing.py
+++ b/xarray/core/indexing.py
@@ -911,6 +911,10 @@ class PandasIndexAdapter(ExplicitlyIndexedNDArrayMixin):
                 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)
 


Test patch:
diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py
index c8f74762..f5125796 100644
--- a/xarray/tests/test_variable.py
+++ b/xarray/tests/test_variable.py
@@ -1719,6 +1719,13 @@ class TestIndexVariable(TestCase, VariableSubclassTestCases):
             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