MATLAB: Rounding date time to nearest half hour wihtin a table

date timedateshiftdatetimenearest 30 minutesnearest half hourrounding

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!

Best Answer

An alternate way
%% A slightly modified example from the documentation
MeasurementTime = datetime({'2015-12-18 08:03:05';'2015-12-18 10:33:17';'2015-12-18 12:53:13'});
Temp = [37.3;39.1;42.3];
Pressure = [30.1;30.03;29.9];
WindSpeed = [13.4;6.5;7.3];
TT = timetable(MeasurementTime,Temp,Pressure,WindSpeed);
vec = datevec( TT.MeasurementTime );
v5 = vec(:,5)+vec(:,6)/60;
vec(:,5) = round(v5/30)*30;
vec(:,6) = 0;
TT.MeasurementTime = datetime( vec );
>> TT
TT =
3×3 timetable
MeasurementTime Temp Pressure WindSpeed
____________________ ____ ________ _________
18-Dec-2015 08:00:00 37.3 30.1 13.4
18-Dec-2015 10:30:00 39.1 30.03 6.5
18-Dec-2015 13:00:00 42.3 29.9 7.3
>>
Afterthought
In the example above
TT.MeasurementTime = datetime( vec );
replaces the original datetime object of the table with a new datetime object. Properties, like Format, of this new object will have default values. Values set by the user will thus be lost. And creating a new object might be inefficient. Thus, replace
TT.MeasurementTime = datetime( vec );
by
TT.MeasurementTime.Minute = vec(:,5);
TT.MeasurementTime.Second = 0;
And why involve datevec() when the code below is both shorter and cleaner
%%
mm = TT.MeasurementTime.Minute + TT.MeasurementTime.Second/60;
mm = round(mm/30)*30;
TT.MeasurementTime.Minute = mm;
TT.MeasurementTime.Second = 0;