I want the unit of time to be "hours since" like other which have unit is "day since"
Asked
Active
Viewed 411 times
1 Answers
0
I usually have a code like this:
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()
# --------------------------------------------
In this example I also wanted to change the variable type from "float" to "double" and therefore made a new file using ncap2 instead of ordinary copy (cp oldfile newfile).

msi_gerva
- 2,021
- 3
- 22
- 28
-
Thanks for replying ,Do you have any idea for how to change variable name in netcdf files like from "TIME" to i have to change it into "time"? – sonal Oct 14 '22 at 05:37
-
If you have nco (https://nco.sourceforge.net/) tools available, you can use `ncrename`. To rename the variable TIME, you can do "ncrename -v TIME,time filein fileout". To rename dimension as well, you have to use "ncrename -d TIME, time filein fileout". – msi_gerva Oct 14 '22 at 14:34