divide cell array into date and time columns

1 view (last 30 days)
I have a cell array with 6 columns and 10000 rows. The first column contains date and time in the format eg. '31/12/2001 12:57:03'. I want to seperate the first column into two seperate columns, one for date and the other for time. Then I want to convert the date to dateserial number.
thanks

Accepted Answer

Walter Roberson
Walter Roberson on 7 Oct 2017
temp = regexp(YourCellArray(:,1), '\s+', 'split');
datecol = cellfun(@(C) C{1}, temp, 'uniform', 0);
timecol = cellfun(@(C) C{2}, temp, 'uniform', 0)
serialdates = datenum(datecol);
If you do not actually need the time column, then this can be abbreviated down to
serialdates = datenum( regexprep(YourCellArray(:,1), '\s.*', '') );
  2 Comments
AA
AA on 7 Oct 2017
I want to display the time column as well but it i get the error message: index exceeds matrix dimensions. I do not know what the problem is. My aim is the convert the time as minutes after midnight with the following formula:
>> [60,1]*sscanf( '12:48', '%2d:%2d')
ans =
768
Walter Roberson
Walter Roberson on 8 Oct 2017
YourCellArray{1,1} = '31/12/2001 12:57:03';
YourCellArray{2,1} = '30/12/2001 13:18:03';
then
temp = regexp(YourCellArray(:,1), '[\s:]+', 'split');
datecol = cellfun(@(C) C{1}, temp, 'uniform', 0);
hourcol = cellfun(@(C) C{2}, temp, 'uniform', 0);
mincol = cellfun(@(C) C{2}, temp, 'uniform', 0);
since_midnight = str2double(hourcol) * 60 + str2double(mincol);
... or,
temp = datevec(YourCellArray(:,1));
since_midnight = temp(:,4) * 60 + temp(:,5);

Sign in to comment.

More Answers (1)

Peter Perkins
Peter Perkins on 13 Oct 2017
Think about using datetime and duration instead of datenum:
>> dt = datetime({'30/12/2015 15:54:30';'30/12/2015 15:54:30';'30/12/2015 15:54:30'},'InputFormat','dd/MM/yyyy HH:mm:ss')
dt =
3×1 datetime array
30-Dec-2015 15:54:30
30-Dec-2015 15:54:30
30-Dec-2015 15:54:30
>> d = dateshift(dt,'start','day')
d =
3×1 datetime array
30-Dec-2015 00:00:00
30-Dec-2015 00:00:00
30-Dec-2015 00:00:00
>> t = timeofday(dt)
t =
3×1 duration array
15:54:30
15:54:30
15:54:30

Categories

Find more on Data Type Conversion 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!