I am quite new to python and I read some previous related questions, but those does not answer exactly my question:
I have an already sliced .nc file for precipitation for my case study. In python I do the processing, and I need the time in 3 different columns [2015 01 31], though is given me to in one column YYYYMMDD [20150101 20150131 .... 20171221]
I have tried using the module netCDF4 and numpy to process and split the data as I required it.
#Script for reading .nc files using the netcdf4 module in Python
import numpy as np
import netCDF4 as nc
os. chdir('/mnt/lustre02/work/ch0636/g260150/sims/validation/selectedmodelRCPs/RCP2.6/Model1/')
#extract time in a single array to append it to the whole dly. weather file
data=nc.Dataset('precipitation.nc','r')
time=data.variables['time'][:]
b=np.zeros((time.size,1))
b[:,0]=time
#Extracting time sections: year, month, day
year=[]
month=[]
day=[]
for i in range(len(b)):
year.append(b[i][0:4])
month.append(b[i][4:6])
day.append(b[i][6:])
print(day)
print(month)
print(year)
Running this part gives that day is the whole date including year, month and day. Month and day are empty arrays. I am not really sure how I could actually approach this in a proper way, that helps me getting what I need for my further processing.
To get the arrays of year, month and day using your solution, I suggest modification like this:
year=[]
month=[]
day=[]
for i in range(len(b)):
yval=np.floor(b[i]/10000.)
mval=np.floor((b[i]-yval*10000.)/100.)
dval=np.floor(b[i]-yval*10000.-mval*100.)
year.append(int(yval))
month.append(int(mval))
day.append(int(dval))
print(day)
print(month)
print(year)
Nevertheless, I can also suggest a code like this, where we first convert the time to date values and then extract the years, months and days:
# other way:
import datetime
def get_date(datevalin):
fraction_of_day=datevalin-np.floor(datevalin)
d0=datetime.datetime.strptime(str(int(np.floor(datevalin))),'%Y%m%d')
dval=d0+datetime.timedelta(seconds=fraction_of_day*24.*3600)
return dval
dates=[get_date(val) for val in time];
year=[val.year for val in dates];
month=[val.month for val in dates];
day=[val.day for val in dates];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.