MATLAB Answers

Convert Date to DATENUM format

6 views (last 30 days)
Hi everyone,
I have a .csv file with a list of dates in column 3 which I would like to convert to datenum format.
I'm new to matlab but from what I have learned so far, I think I should write code to do this for one line, and then apply a for loop so it applies to every line of data?
-my code suggests I have many .csv files but for now I only have one. I am writing code which in the future I will be able to apply to large data sets.
At the moment I have this:
%Convert date into datenum format-calculates time as the number of days
%from January 0, 0000.
dd = 'input_data'; %label input folder as 'dd'
nowd = cd; %marks current current directory as 'nowd'
cd(dd); %go to input folder (which is within CD)
d = dir('*.csv'); %mark all csv files within current folder
cd(nowd) %GO BACK TO date folder
%In the current .csv file, the date is in column 3.;
c = strsplit(tline,','); %this moves down the rows, separating by comma???
date = datenum(c{3},'dd-mm-yyyy');
I realise I haven't yet put in a for loop. I just wanted to try to get it to work for one line, but I'm not sure if I got my commands all mixed up, or if this is even the correct approach.
Stephen Cobeldick
Stephen Cobeldick on 8 May 2019
"Do you know when, when I use strsplit, I split the column titles, rather than the values I derived from fgetl?"
"Something to do with c{3} which is identifying the header only??"
The commands fgetl and fgets read one line each time they are called. They do not read the entire file content, just one line. You call fgetl just once in your code, so I would expect it to return the first line from that file (that would appear be a file header). If you want to import multiple lines from the file, then you will need to call fgetl multiple times (e.g. in a loop).
But doing so would be rather tiresome and likely inefficient. Because importing file data is such a common need, MATLAB already includes many function for different file types, that will efficiently parse the entire file at once (rather than line-by-line):

Sign in to comment.

Accepted Answer

Peter Perkins
Peter Perkins on 8 May 2019
"which I would like to convert to datenum format."
Louise, you really don't want to do that. Any of it. Unless you are using a pretty old version of MATLAB, like pior to R2014b, I strongly recommend that you use readtable, and your timestamps will come in as datetimes. Then convert to a timetable. In R2019a, you can use readtimetable.
In versions older than about R2017b, you'll probably get text timestamps, not datetime, but you can convert.
Peter Perkins
Peter Perkins on 14 May 2019
Do you really have a good reason to go back to using datenums? You are very likely to be much happier using datetimes.

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!