How can I create time in proper format to export to a netCDF (.nc) file in MATLAB?

18 views (last 30 days)
Data
I am trying to create a time dimension using this
'''
t1 = datetime(1901,1,1);
t2 = datetime(2016,12,31);
t = t1:t2;
'''
And create a netCDF file using this
'''
nccreate('prec.nc','Prec',...
'Dimensions',{'time' 42369 'lon' 135 'lat' 129},...
'Format', 'netcdf4');
'''
What I have tried
ncwrite('prec.nc', 'time', t);
Error Message
Error using cast
Unsupported data type for conversion: 'datetime'.
Error in internal.matlab.imagesci.nc/write (line 778)
scale_factor = cast(1, class(varData));
Error in ncwrite (line 87)
ncObj.write(varName, varData, start, stride);
Question
How can I create a daily time dimension that I can write out to a netCDF file? What is the proper date type for this conversion?

Answers (1)

KSSV
KSSV on 12 Feb 2020
Convert the dates into numbers using datenum. These numbers can be written into netCDF file. Read about datenum.
  3 Comments
KSSV
KSSV on 13 Feb 2020
t1 = datetime(1901,1,1);
t2 = datetime(2016,12,31);
t = t1:t2;
t = datenum(t) ;
YOu check the conversion in MATLAB itself before writitng to nc. Convert datetime to datenum and vice versa..once it is confirmed..then write to .nc
Ravi Raj
Ravi Raj on 20 Feb 2020
I have converted datenum into datetime and vice-versa. You can see in following commands:
TRIED
>> t1 = datenum(1901,1,1)
t1 =
694327
>> t2 = datenum(2016,12,31)
t2 =
736695
>> x1 = datetime(t1,'ConvertFrom','datenum')
x1 =
datetime
01-Jan-1901 00:00:00
>> x2 = datetime(t2,'ConvertFrom','datenum')
x2 =
datetime
31-Dec-2016 00:00:00
BUT
While writting into nc format the datenum 694327 is returning as 3802-01-02 and 736695 as 3918-01-02 instead of returning as (1901,1,1) and (2016,12,31) respectively.
I am attaching here the screenshot of returning value in nc format. Please have a look.

Sign in to comment.

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!