error using etime (datevec)
6 views (last 30 days)
Show older comments
I have a csv file with times for experiment start and end. I'm trying to use etime to work out the time difference but im getting the following error. Can anybody help?
fid = fopen('time.csv');
out = textscan(fid,'%s %f %f %s','delimiter',',','headerlines',1);
fclose(fid);
com = out{1};
com2 = out{2};
com3 = out{3};
start_t = out{4};
dt2 = start_t(1);
gap_sec = etime(datevec(dt2),datevec(dt1));
time = gap_sec + time;
Error using datevec (line 225)
Failed to lookup month of year.
0 Comments
Answers (2)
Star Strider
on 16 Feb 2022
If R2014b or later is available, try this —
T1 = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/896495/time.csv')
C = regexp(T1{:,1}, '\d*\.\d*E\d', 'match');
n = cell2mat(cellfun(@(x)str2double(x), C, 'Unif',0));
Dates = datetime(n(:,2), 'ConvertFrom','Posixtime');
ElapsedTime = diff(Dates);
ElapsedTime.Format = 'hh:mm:ss.SSS'
The initial regexp call returns the POSIX numbers as strings. The ‘n’ and ‘Dates’ assignments extract the numerical data from the strings and convert them to datetime arrays. Using the diff funciton (to get the elapsed time) automatically returns the result as a duration array (here a scalar) and the last line sets the display 'Format' to show the milliseconds as well.
.
0 Comments
Seth Furman
on 17 Feb 2022
Edited: Seth Furman
on 17 Feb 2022
We can import the table using import options to specify the delimiter and datetime format.
See also the following documentation pages.
fname = "https://www.mathworks.com/matlabcentral/answers/uploaded_files/896495/time.csv";
opts = detectImportOptions(fname,"Delimiter",",","TextType","string","VariableNamingRule","preserve")
opts.VariableTypes{4} = 'datetime';
inputFormat = "uuuu-MM-dd HH:mm:ss.SSS ZZZZ";
opts = setvaropts(opts,4,"InputFormat",inputFormat,"TimeZone","UTC");
t = readtable(fname,opts)
diff(t{:,4})
0 Comments
See Also
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!