(timezone aware) datetime in netcdf using python
<p>I'm trying to save a timeserie in a netcdf file. According to documentation I found, this can be done using the date2num method from the netCDF4 module. I can't get it working however (see example below):</p>

<pre><code>from datetime import datetime as dt
from netCDF4 import Dataset
from netCDF4 import num2date, date2num
import pytz

filename = 'test.nc'
root = Dataset(filename, 'w', format='NETCDF4_CLASSIC')
root.name = 'test'

# create dimension
root.createDimension('datetime', None)

# create variable
timeserie = root.createVariable('timeserie', 'f4', ('datetime',))
timeserie.units = 'days since 1970-01-01 00:00:00 UTC' # reference: epoch
timeserie.calendar = 'gregorian'

# create testList
listDT = [dt.now(pytz.utc), dt(1970, 1, 2, 12, 0, 0, 0, pytz.utc)]
print date2num(listDT, units=timeserie.units, calendar=timeserie.calendar)

root.close()
</code></pre>

<p>The error it gives me:</p>

<blockquote>
<pre><code>Traceback (most recent call last):
  File "test.py", line 20, in &lt;module&gt;
    print date2num(listDT, units=timeserie.units, calendar=timeserie.calendar)
  File "netCDF4\_netCDF4.pyx", line 5128, in netCDF4._netCDF4.date2num (netCDF4\_netCDF4.c:60367)
TypeError: can't subtract offset-naive and offset-aware datetimes
</code></pre>
</blockquote>

<p>How would I save datetime data (preferably timezone aware) to netcdf using python?</p>

<p>The <a href="http://unidata.github.io/netcdf4-python/#netCDF4.date2num" rel="nofollow">date2num() doc</a> says that the datetime object must be UTC. A number cannot be timezone aware,unless it is UTC. Would cause great problems with standard/daylight time transitions.</p>

<p>Try</p>

<pre><code>listDT = [dt.now(), dt(1970, 1, 2, 12, 0, 0, 0)]
print date2num(listDT, units=timeserie.units, calendar=timeserie.calendar)
</code></pre>

<p>To demonstrate that it is timezone aware, try Eastern offset as units.</p>

<pre><code>print date2num(listDT, units='days since 1970-01-01 00:00:00-04:00', calendar=timeserie.calendar)
</code></pre>

python datetime netcdf