spliting date and time strings in a table

18 views (last 30 days)
I am importing data from a large csv into a table. One column in the csv is a string of dates and times. I want to split this column so that each has its own column and variable in the table. I have tried adding multiple delimiters but readtable does not seem to be able to handle this. Now, I am trying to read the table in as is then split the date and time using a for loop. The date and time are separated by a blank space.
N = size(x,1);
x.Date = cell(N,1);
x.Time = cell(N,1);
for n = 1:N
x.Date{n} = x.DateTime{n}(1:strfind(x.DateTime{n},' ')-1);
x.Time{n} = x.DateTime{n}(strfind(x.DateTime{n},' ')+1:end);
end
However, this takes a really long time as N can be large. Is there a better and quicker way to do this?
Thanks

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 26 Jun 2015
data={'23/06/2015 00:50:12';'24/06/2015 12:30:45';'25/06/2015 13:00:01'}
a=datevec(data,'dd/mm/yyyy HH:MM:SS')
date=datestr(datenum(a),'dd/mm/yyyy')
time=datestr(datenum(a),'HH:MM:SS')
  2 Comments
Stephen23
Stephen23 on 20 Jul 2015
Edited: Stephen23 on 20 Jul 2015
One can also convert directly to serial date numbers:
a = datenum(data,'dd/mm/yyyy HH:MM:SS')
date = datestr(a,'dd/mm/yyyy')
time = datestr(a,'HH:MM:SS')

Sign in to comment.

More Answers (1)

Peter Perkins
Peter Perkins on 6 Jul 2015
If all you want is strings, Azzi's answer works. But you may find the following more useful. Given this file:
timestamp,x
23-Jun-2015 00:50:12,-0.43359
24-Jun-2015 12:30:45,0.34262
25-Jun-2015 13:00:01,3.5784
The following creates a table with a datetime variable for the date, and a duration for the time:
>> readtable('myfile.csv','Format','%D%f');
>> t.date = dateshift(t.timestamp,'start','day');
>> t.date.Format = 'dd-MMM-yyyy';
>> t.time = timeofday(t.timestamp);
>> t.timestamp = []
t =
x date time
_______ ___________ ________
2.7694 23-Jun-2015 00:50:12
-1.3499 24-Jun-2015 12:30:45
3.0349 25-Jun-2015 13:00:01
  1 Comment
Zargham Ali
Zargham Ali on 20 Jul 2015
hi i want to add a string of date and time in the first column of excel file. With start and end date and time shown 24 hourly for one day. i would be grateful for your help. Format is below 01/01/2015 00:00;
01/01/2015 01:00; . 01/01/2015 24:00 . 02/01/2015 00:00 . . 02/01/2015 01:00 . .

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!