Stream: python-questions
Topic: writing list of dates to netcdf
Isla Simpson (Aug 10 2021 at 01:00):
Hello, I also have something with non-standard calendars that I have been struggling with. I want to output the following list of dates to netcdf. It's for a piControl so the years start at 1.
[array(cftime.DatetimeNoLeap(4, 2, 2, 0, 0, 0, 0), dtype=object), array(cftime.DatetimeNoLeap(8, 2, 10, 0, 0, 0, 0), dtype=object), array(cftime.DatetimeNoLeap(9, 4, 2, 0, 0, 0, 0), dtype=object)]
I have tried:
(1) Convert this list to an xarray data array and then use "to_netcdf": this gives unable to infer dtype on variable 'sswdate'; xarray cannot serialize arbitrary Python objects
(2) Tried to convert to a datetimeindex instead.
- (a) pd.to_datetime(datelist): this gives <class 'numpy.ndarray'> is not convertible to datetime
- (b) datelist.indexes.to_datetimeindex(): this gives 'list' object has no attribute 'indexes'
Can anyone advise me as to how best to deal with this list of dates and get them into a netcdf file? Converting to the datetimeindex is what I've done for similar problems before, but I guess something is missing here.
Thanks for your help,
Isla
Deepak Cherian (Aug 10 2021 at 01:09):
Hi Isla,
The weird thing about your list is it is a list of array of cftime objects. That ends up confusing the software
Your 2b solution assumes datelist
is an xarray thing (which does have an indexes
property). But datelist
is a list so that's the reason for the error
Here I pull out each individual item from the array and things work
import cftime
from numpy import array
time = [
array(cftime.DatetimeNoLeap(4, 2, 2, 0, 0, 0, 0), dtype=object),
array(cftime.DatetimeNoLeap(8, 2, 10, 0, 0, 0, 0), dtype=object),
array(cftime.DatetimeNoLeap(9, 4, 2, 0, 0, 0, 0), dtype=object),
]
xr.DataArray([t.item() for t in time], dims="time").to_netcdf("time.nc")
Isla Simpson (Aug 10 2021 at 01:16):
Wow, thanks for the fast response! Indeed, that has done the trick. Thanks a lot!
Last updated: Jan 30 2022 at 12:01 UTC