MATLAB Answers

How to convert column datetime to datenum?

265 views (last 30 days)
HI everyone,
I have a .csv file with a datetime column, in the format 'yyyy/m/d hh:mm:ss', for example: '2019/5/2 10:21:25'.
So, earlier dates in the month will be yyyy/m/d but later this will change to yyyy/mm/dd.
I want to convert these datetimes to datenum, as code I am using from a colleague which relies on datenum as an input.
I tried the following, where data.DateTime is a column in a table of such datetimes.
formatIn = 'yyyy/m/d HH:MM:SS';
However, I get the error "too many input arguments".
Thank you in advance for your help!
Louise Wilson
Louise Wilson on 9 May 2019
Thank you Walter. I tried that but get some errors:
>> datenumber=datenum({data.DateTime},formatIn);
Error using datenum (line 190)
DATENUM failed.
Caused by:
Error using datenum (line 118)
The input to DATENUM was not an array of character vectors.

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 9 May 2019
Edited: Stephen Cobeldick on 9 May 2019
It is not clear from your example what class data has: a table or a non-scalar structure or .. ?
In any case, datetime objects do not need a format to be converted to serial date numbers:
DN = datenum(data.DateTime) % If data is a table or a scalar structure
DN = datenum([data.DateTime]) % If data is a non-scalar structure
As the documentation shows, the format argument is only used for date string inputs:
Louise Wilson
Louise Wilson on 9 May 2019
Hi Walter,
Thank you. I am new to Matlab so don't fully understand your answer, but I have everything working now...
I had used readtable like you said and made adjustments to the formatting of each cell.
Here is my full code, what do you think?
dd = 'input_data';
nowd = cd; %current folder
cd(dd); %go to input folder
d = dir('*.csv');
%cd(nowd); %GO BACK TO current folder
for j=1:length(d)
%data=table2timetable(dat, 'RowTimes', 'LOCALTIME'); %orientate timetable using 'localtime' as the time vector
fid = fopen(fullfile(dd,filename)); %open file
%%Put Date and Time into One Column
dates=datetime(data.LOCALDATE, 'Format', 'y/M/d'); %convert date to datetime array
times=datenum(data.LOCALTIME); %datenum-serial date number
t=table(dates,times); %create 2x table of dates and times
dates=datetime(t.dates,'Format', 'y/M/d hh:mm:ss'); %format date cells
times=datetime(t.times,'ConvertFrom','datenum','Format',... %format time cells
'y/M/d hh:mm:ss');
fullt=dates+timeofday(times); %date and time into one column
data.DateTime=fullt; %append column onto data table
%%Convert DateTime to DateNum
%datevec(datenumber); %check that the datenumbers are different
%%Remove date/time columns I am not interested in
data_new=removevars(data, [1 2 3 4 5 6 8 10 13]);
%%Add callsign or vessel number of boat:

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!