add hours to timetable time cell array
Ältere Kommentare anzeigen
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'.
Antworten (3)
% create table that duplicates illustrated
tT=table({'2026-05-23 09:55';'2026-05-23 09:50'},[271;265], ...
'VariableNames',{'datetime','cfs'})
tT.datetime=datetime(tT.datetime,'Format','yyyy-MM-dd HH:mm') % convert to datetime, display to minute precision
tT.datetime=tT.datetime-hours(10) % subtract 10 hours
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')
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.
Star Strider
vor etwa 2 Stunden
Bearbeitet: dpb
vor 44 Minuten
Try something like this --
A = {{'2026-05-23 09:55'} 271
{'2026-05-23 09:50'} 265};
T1 = cell2table(A, VariableNames={'Date','cfs'})
T1.Date = datetime(T1.Date, InputFormat='yyyy-MM-dd HH:mm', ...
Format='yyyy-MM-dd HH:mm') - hours(10)
.
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>>
.
Louis
vor 2 Minuten
0 Stimmen
Kategorien
Mehr zu Dates and Time finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!