Rounding date time to nearest half hour wihtin a table
Show older comments
Hi all,
I've been searching through previous Q&A's but cant seem to find something that works. I have a table with over 800 rows and would like to round the date time to the nearest half hour. I have tried dateshift but get the error: Undefined function 'dateshift' for input arguments of type 'cell'.
Is there anyway of rounding these within the table?
Thanks!
Accepted Answer
More Answers (1)
If your datetime values are stored in a cell array, first convert them to a datetime array using,
datetimeValues = [datetimeCell{:}]';
% Remove the transpose (') at the end if dateTimeCell is a row vector.
Then round all datetime values down to the earliest hour.
% Create demo data
datetimeValues = datetime(2020,02,05) + minutes(0:3:60)';
% Round to the nearest hour
dateTimeShifted = dateshift(datetimeValues,'start','hour');
Then add 30 minutes for datetime values that had minutes between 15-45 and add 1 hour to datetime values that had minutes greater than or equal to 45.
minuteValues = minute(datetimeValues);
dateTimeShifted(minuteValues >= 15 & minuteValues < 45) = dateTimeShifted(minuteValues >= 15 & minuteValues < 45) + minutes(30);
dateTimeShifted(minuteValues >= 45) = dateTimeShifted(minuteValues >= 45) + hours(1);
Here are two ways to test the results.
Create a table of the original times, shifted times, and the duration between those values. The 'difference' column should not contain any values larger than +/- 15 minutes.
table(datetimeValues, dateTimeShifted, minutes(datetimeValues-dateTimeShifted), ...
'VariableNames', {'Original','Shifted','difference'})
% Result (only the first few rows)
% Original Shifted difference
% ____________________ ____________________ __________
% 05-Feb-2020 00:00:00 05-Feb-2020 00:00:00 0
% 05-Feb-2020 00:03:00 05-Feb-2020 00:00:00 3
% 05-Feb-2020 00:06:00 05-Feb-2020 00:00:00 6
% 05-Feb-2020 00:09:00 05-Feb-2020 00:00:00 9
% 05-Feb-2020 00:12:00 05-Feb-2020 00:00:00 12
Duration between the original and shifted times as a function of the original times. Values along the y axis should not exceed +/- 15 minutes.
plot(dateTimeShifted, minutes(datetimeValues-dateTimeShifted), 'o')
grid on; xlabel('shifted datetime'); ylabel('\Delta minutes')
Addendum: I just noticed that these values are within a table. Here are the lines of code above adapted for a table with column "datetimeValues".
T.datetimeValues = [T.datetimeValues{:}]';
dateTimeShifted = dateshift(T.Var1,'start','hour');
minuteValues = minute(datetimeValues);
dateTimeShifted(minuteValues >= 15 & minuteValues < 45) = dateTimeShifted(minuteValues >= 15 & minuteValues < 45) + minutes(30);
dateTimeShifted(minuteValues >= 45) = dateTimeShifted(minuteValues >= 45) + hours(1);
T.Var1 = dateTimeShifted;
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!