在python中的netcdf变量中更改单位

问题描述

我在Python中有一个netCDF文件,其中时间变量的单位为days_since_Jan11900xarray包无法读取。它引发错误

unable to decode time units 'days_since_Jan11900' with 'the default calendar'. Try opening your dataset with decode_times=False or installing cftime if it is not installed.

我不想使用decode_times,而只是将其更改为days_since_0。是从1/1/0000天。

如何将netCDF中的单位更改为可读的?

<class 'netCDF4._netCDF4.Variable'>
float64 days(time)
    units: days_since_Jan11900
    long_name: calendar_days
unlimited dimensions: 
current shape = (87600,)
filling on,default _FillValue of 9.969209968386869e+36 used

解决方法

如果您使用的是Unix,则可以尝试使用CDO更改日历。以下应该可以解决您的问题:

cdo -L  -setreftime,0001-01-01  -settaxis,0001-01-01,0:00:00,1day  -setcalendar,standard infile.nc outfile.nc 

我将时间设置为1年,因为我认为任何有效的日历中都没有0年。

,

我按照要求自行在Python中解决了问题,而不是通过cdo解决了。这是我的做法,非常简单:

ds['days'] = ds.days - 730966
ds.days.attrs['units'] = 'days since 1860-01-01'
ds.to_netcdf(path + 'name_of_file.nc')

730966是我在days数组中的起始值,因此我减去了该值,然后将单位更改为适当的单位,在我的情况下为days since 1860-01-01