Repository: pydata/xarray

Issue:
to_netcdf() fails because of datetime encoding
#### Simple example:

```python
import numpy as np
from datetime import datetime, timedelta
import xarray

# "time" coordinate
dt = datetime(1999, 1, 1)
dts = np.array([dt + timedelta(days=x) for x in range(10)])
coords = {'time': dts}

# simple float data
data = np.arange(10)
vrbls = {'foo': (('time',), data)}

# create the Dataset
ds = xarray.Dataset(vrbls, coords)

# encode the time coordinate
units = 'days since 1900-01-01'
ds.time.encoding['units'] = units

# write to netcdf
ds.to_netcdf('test.nc')

```
#### Problem description

When I run the above, I get the following error when executing the last line:
**`ValueError: unsupported dtype for netCDF4 variable: datetime64[ns]`**

The documentation indicates that datetime and datetime64 objects are both supported by xarray and should write to netcdf just fine when supplied "units" for encoding (this code fails with or without the encoding lines). Any Idea when is going wrong here?

#### Output of ``xr.show_versions()``

<details>
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.2.final.0
python-bits: 64
OS: Linux
OS-release: 4.9.0-8-amd64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

xarray: 0.10.9
pandas: 0.20.3
numpy: 1.13.1
scipy: 0.19.1
netCDF4: 1.4.2
h5netcdf: 0.5.0
h5py: 2.8.0
Nio: None
zarr: None
cftime: 1.0.1
PseudonetCDF: None
rasterio: None
iris: None
bottleneck: 1.2.1
cyordereddict: None
dask: 0.16.0
distributed: 1.20.1
matplotlib: 2.1.0
cartopy: None
seaborn: 0.8.0
setuptools: 27.2.0
pip: 9.0.1
conda: 4.5.11
pytest: 3.1.3
IPython: 6.1.0
sphinx: 1.6.2
</details>


Discussion:
pep8speaks: Hello @dcherian! Thanks for submitting the PR.

 - There are no PEP8 issues in the file [`xarray/core/variable.py`](https://github.com/dcherian/xarray/blob/b2ade2e4d2eda90dd09fde8ff717ee3dd1749332/xarray/core/variable.py) !

 - There are no PEP8 issues in the file [`xarray/tests/test_variable.py`](https://github.com/dcherian/xarray/blob/b2ade2e4d2eda90dd09fde8ff717ee3dd1749332/xarray/tests/test_variable.py) !



Patch:
diff --git a/doc/api-hidden.rst b/doc/api-hidden.rst
index 0e8143c7..0d8189d2 100644
--- a/doc/api-hidden.rst
+++ b/doc/api-hidden.rst
@@ -39,7 +39,6 @@
    Dataset.imag
    Dataset.round
    Dataset.real
-   Dataset.T
    Dataset.cumsum
    Dataset.cumprod
    Dataset.rank
diff --git a/doc/whats-new.rst b/doc/whats-new.rst
index 4ae498c3..4497c57e 100644
--- a/doc/whats-new.rst
+++ b/doc/whats-new.rst
@@ -33,6 +33,8 @@ v0.11.0 (unreleased)
 Breaking changes
 ~~~~~~~~~~~~~~~~
 
+- ``Dataset.T`` has been removed as a shortcut for :py:meth:`Dataset.transpose`.
+  Call :py:meth:`Dataset.transpose` directly instead.
 - Iterating over a ``Dataset`` now includes only data variables, not coordinates.
   Similarily, calling ``len`` and ``bool`` on a ``Dataset`` now  
   includes only data variables
@@ -92,6 +94,9 @@ Bug fixes
 - Addition and subtraction operators used with a CFTimeIndex now preserve the
   index's type. (:issue:`2244`).
   By `Spencer Clark <https://github.com/spencerkclark>`_.
+- We now properly handle arrays of ``datetime.datetime`` and ``datetime.timedelta``
+  provided as coordinates. (:issue:`2512`)
+  By `Deepak Cherian <https://github.com/dcherian`_.
 - ``xarray.DataArray.roll`` correctly handles multidimensional arrays.
   (:issue:`2445`)
   By `Keisuke Fujii <https://github.com/fujiisoup>`_.
diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py
index 534029b9..983270cf 100644
--- a/xarray/core/dataset.py
+++ b/xarray/core/dataset.py
@@ -916,13 +916,6 @@ class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords,
         return [self.data_vars, self.coords, {d: self[d] for d in self.dims},
                 LevelCoordinatesSource(self)]
 
-    def __dir__(self):
-        # In order to suppress a deprecation warning in Ipython autocompletion
-        # .T is explicitly removed from __dir__. GH: issue 1675
-        d = super(Dataset, self).__dir__()
-        d.remove('T')
-        return d
-
     def __contains__(self, key):
         """The 'in' operator will return true or false depending on whether
         'key' is an array in the dataset or not.
@@ -2647,13 +2640,6 @@ class Dataset(Mapping, ImplementsDatasetReduce, DataWithCoords,
             ds._variables[name] = var.transpose(*var_dims)
         return ds
 
-    @property
-    def T(self):
-        warnings.warn('xarray.Dataset.T has been deprecated as an alias for '
-                      '`.transpose()`. It will be removed in xarray v0.11.',
-                      FutureWarning, stacklevel=2)
-        return self.transpose()
-
     def dropna(self, dim, how='any', thresh=None, subset=None):
         """Returns a new dataset with dropped labels for missing values along
         the provided dimension.
diff --git a/xarray/core/variable.py b/xarray/core/variable.py
index c003d52a..fefd48b4 100644
--- a/xarray/core/variable.py
+++ b/xarray/core/variable.py
@@ -95,7 +95,7 @@ def as_variable(obj, name=None):
                 'cannot set variable %r with %r-dimensional data '
                 'without explicit dimension names. Pass a tuple of '
                 '(dims, data) instead.' % (name, data.ndim))
-        obj = Variable(name, obj, fastpath=True)
+        obj = Variable(name, data, fastpath=True)
     else:
         raise TypeError('unable to convert object into a variable without an '
                         'explicit list of dimensions: %r' % obj)


Test patch:
diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py
index adc80966..aa226ff1 100644
--- a/xarray/tests/test_dataset.py
+++ b/xarray/tests/test_dataset.py
@@ -3801,10 +3801,6 @@ class TestDataset(object):
         expected = ds.apply(lambda x: x.transpose())
         assert_identical(expected, actual)
 
-        with pytest.warns(FutureWarning):
-            actual = ds.T
-        assert_identical(expected, actual)
-
         actual = ds.transpose('x', 'y')
         expected = ds.apply(lambda x: x.transpose('x', 'y'))
         assert_identical(expected, actual)
diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py
index 52289a15..3753221f 100644
--- a/xarray/tests/test_variable.py
+++ b/xarray/tests/test_variable.py
@@ -992,6 +992,13 @@ class TestVariable(VariableSubclassobjects):
                 ValueError, 'has more than 1-dimension'):
             as_variable(expected, name='x')
 
+        # test datetime, timedelta conversion
+        dt = np.array([datetime(1999, 1, 1) + timedelta(days=x)
+                       for x in range(10)])
+        assert as_variable(dt, 'time').dtype.kind == 'M'
+        td = np.array([timedelta(days=x) for x in range(10)])
+        assert as_variable(td, 'time').dtype.kind == 'm'
+
     def test_repr(self):
         v = Variable(['time', 'x'], [[1, 2, 3], [4, 5, 6]], {'foo': 'bar'})
         expected = dedent("""