add hours to timetable time cell array

I have a table:
datetime cfs
____________________ ____
{'2026-05-23 09:55'} 271
{'2026-05-23 09:50'} 265
I want to subtract 10 hours from each time, to fix a time zone difference. How can I change all the time values in the cell array 'datetime' by a constant value? also, I want to make sure this will keep the dates consistent, i.e. '2026-05-23 9:00' -10 should then be '2026-05-22 23:00'.

Answers (2)

dpb
dpb about 2 hours ago
Edited: dpb 4 minutes ago
% create table that duplicates illustrated
tT=table({'2026-05-23 09:55';'2026-05-23 09:50'},[271;265], ...
'VariableNames',{'datetime','cfs'})
tT = 2×2 table
datetime cfs ____________________ ___ {'2026-05-23 09:55'} 271 {'2026-05-23 09:50'} 265
tT.datetime=datetime(tT.datetime,'Format','yyyy-MM-dd HH:mm') % convert to datetime, display to minute precision
tT = 2×2 table
datetime cfs ________________ ___ 2026-05-23 09:55 271 2026-05-23 09:50 265
tT.datetime=tT.datetime-hours(10) % subtract 10 hours
tT = 2×2 table
datetime cfs ________________ ___ 2026-05-22 23:55 271 2026-05-22 23:50 265
I'd recomend to rename the datetime variable so it doesn't conflict with the builtin DATETIME() function; while it is allowable, it could lead to some confusion. I'd probably choose
tT=renamevars(tT,'datetime','DateTime')
tT = 2×2 table
DateTime cfs ________________ ___ 2026-05-22 23:55 271 2026-05-22 23:50 265
or something similar.
Note that the datetime class keeps time correctly when doing time arithmetic as long as use consistent units such as duration or calendarDuration class variable or function as needed.
As a general rule, you'll be best served by converting date strings to datetime as quickly as feasible; depending upon the way the table was created it might have been possible to have done the conversion when read the data in originally; that part we don't know about since only provided the resultant table containg the cellstr values. Perhaps detectImportOptions might help in that.
Try something like this --
A = {{'2026-05-23 09:55'} 271
{'2026-05-23 09:50'} 265};
T1 = cell2table(A, VariableNames={'Date','cfs'})
T1 = 2×2 table
Date cfs ____________________ ___ {'2026-05-23 09:55'} 271 {'2026-05-23 09:50'} 265
T1.Date = datetime(T1.Date, InputFormat='yyyy-MM-dd HH:mm', ...
Format='yyyy-MM-dd HH:mm') - hours(10)
T1 = 2×2 table
Date cfs ________________ ___ 2026-05-22 23:55 271 2026-05-22 23:50 265
.
EDIT -- (27 May 2026 at 14:07)
Added Format argument to the datetime call.
EDIT - dpb
Wrapped line so subtraction term is visible without scrolling (with maybe larger font than @Star Strider uses--don't get old <grin>>
.

Products

Release

R2023b

Tags

Asked:

about 14 hours ago

Edited:

dpb
about 11 hours ago

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!