解码时间单位为 "years since" 的 netcdf 数据时出现 xarray 错误

xarray error when decoding netcdf data with time units of "years since"

我有一个别人传给我的 netcdf 文件,它使用“自 DATE 以来的年数”:

double time(time) ;
    time:standard_name = "time" ;
    time:long_name = "time" ;
    time:calendar = "proleptic_gregorian" ;
    time:axis = "T" ;
    time:units = "years since 2000-1-1 00:00:00" ;

当我尝试使用 xarray 打开它时出现错误:

ValueError: unable to decode time units 'years since 2000-1-1 00:00:00' with calendar 'proleptic_gregorian'. Try opening your dataset with decode_times=False.

我可以在 decode_times=False 时打开,但我无法分割时间。我发现将单位更改为“以来的天数”解决了错误,但当然弄乱了时间轴(我只是用

覆盖了单位
ncatted -O -a units,time,m,c,"days since 2000-1-1 00:00:00" ./test.nc

作为测试,但没有更新实际时间变量值)

在xarray中打开以“years since”为单位的netcdf数据文件有技巧吗?

我认为这是由于 xarray 无法始终正确解析时间,即使对于 CF-compliant 文件也是如此。我不认为应该为此批评太多,因为能够解析所有内容不是一件小事。

不过,我的nctoolkit包里有解决办法。它有一个内置的 to_xarray 方法。默认情况下,它使用 xarray 来解码时间。但是,对于 xarray 无法解码时间的情况,您可以使用 CDO 来完成:

import nctoolkit as nc
data = nc.open_data("infile.nc")
ds = data.to_xarray(cdo_times = True)

根据经验,CDO 能够或多或少地解码时间,因此这可能会解决您的问题。

问题是 'years since 2000-1-1 00:00:00' 不是 cftime 模块接受的单位。试图解析说:

units must be one of 'seconds', 'minutes', 'hours' or 'days' (or singular version of these), got 'years'

我认为这是因为,如 CF Conventions 中所述,年(和月)不是日历单位,而是分别定义为 365.242198781 天和 year/12。