更改 python 中 netcdf 变量的单位

Change unit in a netcdf variable in python

我在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。自 0000 年 1 月 1 日以来已有几天了。

如何将 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.