Skip to content

to_netcdf() fails because of datetime encoding #2512

Closed
@nick-weber

Description

@nick-weber

Simple example:

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()

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions