MATLAB: Calculate time intervals in an hour

datetimedurationhistcountshourtabletime

I have a table with 2 columns: start time and end time. For each row the interval interval (end time -start time) represents the duration. I need to find the toal duration per each hour. Note that the time intervals not necessarily are restricted to a specific hour. A part of the table looks like:
Start Time End time
13-Sep-2019 04:12:37 13-Sep-2019 04:16:34
13-Sep-2019 04:18:36 13-Sep-2019 04:33:36
13-Sep-2019 04:33:36 13-Sep-2019 04:48:36
13-Sep-2019 04:48:36 13-Sep-2019 05:03:36
13-Sep-2019 05:03:36 13-Sep-2019 05:18:36
13-Sep-2019 05:18:37 13-Sep-2019 05:33:37
13-Sep-2019 05:33:37 13-Sep-2019 05:48:37
13-Sep-2019 05:48:37 13-Sep-2019 06:03:37
13-Sep-2019 06:03:37 13-Sep-2019 06:18:38
13-Sep-2019 06:18:38 13-Sep-2019 06:33:38
The ideal output would be a table with two columns: hour and total time intervals.
Ex:
Hour Total Duration
13-Sep-2109 04:00:00 X
13-Sep-2109 05:00:00 Y
13-Sep-2109 06:00:00 Z

Best Answer

% Create an input data table
startDateStr = {'2014-05-26 04:44:44';
'2014-05-26 04:45:44';
'2014-05-26 05:44:44';
'2014-05-26 05:45:44';
};
endDateStr = {'2014-05-26 04:44:55';
'2014-05-26 04:45:56';
'2014-05-26 05:44:57';
'2014-05-26 05:45:58';
};
startTime = datetime(startDateStr,'InputFormat','yyyy-MM-dd hh:mm:ss');
endTime = datetime(endDateStr,'InputFormat','yyyy-MM-dd hh:mm:ss');
tbl = table(startTime,endTime);
% Find the unique hours, and the index to those hours
hourOfDay = dateshift(tbl.startTime,'start','hour');
[Hour,~,whichHour] = unique(hourOfDay);
% Find the durations (in seconds, but could be something else)
durationsInSeconds = seconds(tbl.endTime - tbl.startTime);
% Find the total duration for each of the unique hours
TotalDuration = accumarray(whichHour,durationsInSeconds);
% Put the result in a table
output = table(Hour,TotalDuration)