Calculate duration from cell with date hours with Matlab 2013a
Show older comments
I have a cell array of more than 16700 rows and 3 column as in the example below:
'01/01/2014' '12:00:00' 'AM'
'01/01/2014' '06:00:00' 'AM'
'01/01/2014' '10:00:00' 'AM'
'01/01/2014' '12:00:00' 'PM'
'09/04/2014' '11:00:00' 'PM'
I would like to calculate the duration of two chosen dates and time (for example the last row-first raw=number of days, hours and seconds). My big problem is that I have a R2013a version of Matlab. So I can't use DateTime, I tried this:
newA = cellfun(@(s) strsplit(s, ' '), DateTime, 'UniformOutput', false);
DateTimeSep = vertcat(newA{:});
%%Calculs de durée et récupération de données
date=datenum(DateTimeSep(:,1),'mm/dd/yyyy');
d=datestr(date(1256,1)-date(1,1), 'dd')
Time=DateTimeSep(10,2)-DateTimeSep(1,2)% I didn't try to consider the AM PM problem yet....
I get d=04 (which is false) and for time I get: "Undefined function 'minus' for input arguments of type 'cell'"
Accepted Answer
More Answers (1)
If using version prior to introduction of datetime, just use date numbers directly...
>> dn=datenum([char(A{:,1}) char(A{:,2}) char(A{:,3})],'mm/dd/yyyyHH:MM:SSAM'); % to datenumbers
>> dt=dn(end)-dn(1); % a difference first-last
>> [y,m,d,h,m,s]=datevec(dt) % numeric difference in y,m,d,...
y =
0
m =
9
d =
2
h =
23
m =
0
s =
0
>> datestr(dt,'dd HH:MM:SS') % as string in days HH:MM:SS
ans =
02 23:00:00
>>
ADDENDUM
Hmmm...I thought datestr and datevec were just a little smarter than are--I was thinking they would take the value 246 days and reflect that in the datestr conversion if used a field of days only. But, they wrap internally to months so if want days and hours of elapsed time use
days=fix(dt);
then can convert from
fracdays=dt=days;
with datevec datestr to get the time fields in whichever form desired.
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!