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'.
답변 (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.
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
대략 4시간 전
편집: Walter Roberson
대략 3시간 전
카테고리
도움말 센터 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!