divide cell array into date and time columns

1 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2017-10-7
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 个评论
AA
AA 2017-10-7
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 2017-10-8
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);

请先登录,再进行评论。

更多回答(1 个)

Peter Perkins
Peter Perkins 2017-10-13
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by