Create a function to find elapsed time with string of date and times through samples?
5 次查看(过去 30 天)
显示 更早的评论
Hi all.
I have a string array of dates in the form: '2016/10/05 1:06:58 PM' or '2016/10/06 3:01:46 AM'.
I am trying to write a function to find the time elapsed between each event be individual sample where each column (of 27) is an individual sample.
I have this:
function [timeBetween] = GetTimeBetweenFills(dateString)
timeBetween = zeros(length(dateString),1);
timeBetween(1) = 0;
for i=2:length(dateString)-1
time1 = datevec(dateString(i),'yyyy/mm/dd HH:MM:SS AM');
time2 = datevec(dateString(i+1),'yyyy/mm/dd HH:MM:SS AM');
timeBetween(i) = etime(time2,time1);
end
end
And I realized that AM and PM changes through the sample, which I don't know how to handle, and I'm having issues running it through this loop to go through each sample:
S = size(SiteDates);
strArray = table2array(SiteDates);
timeBetween = zeros(S(1),S(2));
for j = 1:27
SiDa = strArray(:,j);
timeBetween(:,j) = GetTimeBetweenFills(SiDa);
end
SiteDates is a table and I tried to convert it to an array and have a string array now but MATLAB doesn't like what I've done.
I get the error:
Error using dtstr2dtvecmx
Failed to convert from text to date number.
Error in datevec (line 122)
y = dtstr2dtvecmx(t,icu_dtformat);
Error in GetTimeBetweenFills (line 9)
time1 = datevec(dateString(i),'yyyy/mm/dd HH:MM:SS AM');
Any help would be wonderful. This is my first time working with time in MATLAB.
Thanks!
0 个评论
采纳的回答
Sean de Wolski
2018-7-12
Please please please use datetimes. Then you can just subtract them (and they account for timezones, dst, leap seconds if you want, etc.)...
datetime('now')-datetime("2018-Jul-4 15:34")
For more info:
doc datetime
9 个评论
Steven Lord
2018-7-16
Preallocate timeBetween to be a duration array.
timeBetween = hours(zeros(length(dateString), 1));
The reason you receive that error is that MATLAB doesn't know what double precision value a duration like (for example) y = days(1) + hours(2) + minutes(3) + seconds(4) should be converted into. Some valid possibilities include 1.0855 (the number of days y represents), 26.0511 (the number of hours), 1563.1 (the number of minutes), or 93784 (the number of seconds.)
In your example, in order to store the duration value into the double array timeBetween MATLAB needs to perform that conversion. When timeBetween starts off as a duration array, no conversion is necessary.
For simplicity, I used hours to preallocate timeBetween, but you could use minutes, seconds, days, etc. You can also change the Format property of timeBetween after it has been created if you change your mind about how it should be displayed.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!