如何阻止 xarray 在写出 netcdf 文件时自动更改时间属性?

How to stop xarray from automatically changing time attributes when writing out a netcdf file?

我注意到,在将多个年度 NetCDF 文件连接成一个文件或将时间序列文件拆分为年度组时,xarray 的 .to_netcdf() 会自动更新时间单位。我的意思的例子

# time attribute of the file
ncdump -h file_1970_2017.nc
>>double time(time) ;
    time:_FillValue = NaN ;
    time:units = "Hours since 1900-01-01T00:00:00+00:00" ;
    time:calendar = "proleptic_gregorian" ;

#  after splitting the files into yearly files using group-by method the time attribute is automatically modified

# example
ncdump -h file_splitted_2005.nc
>>double time(time) ;
    time:_FillValue = NaN ;
    time:units = "Hours since 2005-01-01T00:00:00+00:00" ;
    time:calendar = "proleptic_gregorian" ;

当我反之亦然时遇到了同样的问题,即当我将单独的年度文件连接成一个公共文件时。有什么方法可以强制它不更改时间属性吗?从 documentation 看来,'encoding' 论点可能有帮助,但我不知道如何做?

想通了。使用编码参数作为嵌套字典可以实现

# when writing out the dataset ds encoding can be used as
ds.to_netcdf('file_splitted_2005.nc', encoding={'my_variable':{'_FillValue': -999.0},'time':{'units': "seconds since 1900-01-01 00:00:00"}})

如果我没理解错的话,在写出数据时,如果我们的时间数组是一个日期时间对象,xarray 会根据我们指定的单位属性自动重新计算时间值。在那种情况下,它使用引擎盖下的智能日期时间功能。这意味着我还可以指定

'time':{'units': "seconds since 2000-01-01 00:00:00"}

它会自动重新计算它存储在时间数组中的值,让我们的生活更轻松。