How to use textscan to import time value (hh:mm:ss)

3 views (last 30 days)
I need to import time values in a given column to an array using textscan. I can't seem to be able to find the correct format spec to do this.
Attached is the file I am trying to import from. The row titled 'Start Time" is what I want. The values begin in row 22 column 2 and are in format (hh:mm:ss).
The import data tool uses the below format however gives me rounded values numerical values that are not helpful. How can I edit this to give me what I want
delimiter = ',';
if nargin<=2
startRow = 22;
endRow = 22;
end
formatSpec = '%*s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\n\r]';
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines', startRow(1)-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');

Accepted Answer

Akira Agata
Akira Agata on 23 Oct 2018
I think it's better to do it step-by-step, like:
% Read the file
fid = fopen('181018_PL.txt','r');
c = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
% Extract the line starts with 'Start Time'
idx = startsWith(c{1},'Start Time');
str = c{1}{idx};
% Split the line and eliminate 'Start Time'
dataArray = strsplit(str,',');
dataArray(1) = [];
% Convert to datetime
dataArray = datetime(dataArray);
  3 Comments
Akira Agata
Akira Agata on 24 Oct 2018
Seems strange. In your environment, what is the output variable c{1} ? Since delimiter is set to '\n', the input text file will be separated into each line. As a result, c{1} should be 155x1 cell array.
% Read the file
fid = fopen('181018_PL.txt','r');
c = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
Guy Burke
Guy Burke on 24 Oct 2018
It worked! I was using the wrong syntax for the delimiter. Thanks for much!

Sign in to comment.

More Answers (1)

Peter Perkins
Peter Perkins on 31 Oct 2018
This is a row-oriented file, I'll let you figure out how to best get that into MATLAB. But if the question is how to turn those "time of day" timestamps into durations, in R2018a you can just do that:
>> duration({'12:08:59','12:14:00','12:18:59','12:23:59'},'Format','hh:mm:ss')
ans =
1×4 duration array
12:08:59 12:14:00 12:18:59 12:23:59
Prior to that, you can use text2duration from the FEX.

Community Treasure Hunt

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

Start Hunting!