【问题标题】:how to change the unit of time variable in NetCdf files using python如何使用python更改NetCdf文件中的时间单位变量
【发布时间】:2022-10-06 20:29:06
【问题描述】:

标签: python time dimensions netcdf4 code-climate


【解决方案1】:

我通常有这样的代码:

import numpy as np
import os, subprocess
from netCDF4 import num2date,date2num,Dataset
# --------------------
filein = 'bdy.3d.climatology.nc'
fileout= 'bdy.3d.climatology.from1970.nc'
newunit = 'seconds since 1970-01-01 00:00:00'
# ------------------------------
#cstr = 'cp '+filein+' '+fileout
cstr = 'ncap2 -s "time=double(time)"'+' '+filein+' '+fileout
subprocess.call(cstr,shell=True)
# ------------------------------

ncout = Dataset(fileout,'a');
timevar = ncout.variables['time'];
timein = timevar[:];
# --------------------------------------------
datesin = num2date(timein,timevar.units);
timevar.setncattr('units',newunit)
timevar[:] = date2num(datesin,newunit)
ncout.close()
# --------------------------------------------

在此示例中,我还想将变量类型从“float”更改为“double”,因此使用 ncap2 而不是普通副本(cp oldfile newfile)创建了一个新文件。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2021-02-07
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 2016-02-15
    • 1970-01-01
    相关资源
    最近更新 更多