필터 지우기
필터 지우기

Combining two datetime columns into one

조회 수: 35 (최근 30일)
Autumn P
Autumn P 2022년 3월 9일
댓글: Star Strider 2022년 3월 9일
Hi
I am trying to combine two columns in a table that are formated as datetime. Date is in format 'mm/dd/yyy' and Time is in format 'HH:mm'
I have tried:
%Obs_data.Timestamp = Obs_data.Date + Obs_data.Time;
Error
Addition is not defined between datetime arrays.

채택된 답변

Star Strider
Star Strider 2022년 3월 9일
Another option is to use timeofday
Date = repmat(datetime('now','Format','MM/dd/yyyy'), 3, 1);
Time = datetime('now','Format','HH:mm','Timezone','UTC-7') + hours(0:2).';
Obs_data = table(Date,Time)
Obs_data = 3×2 table
Date Time __________ _____ 03/09/2022 08:54 03/09/2022 09:54 03/09/2022 10:54
Obs_data.Timestamp = Obs_data.Date + timeofday(Obs_data.Time)
Obs_data = 3×3 table
Date Time Timestamp __________ _____ __________ 03/09/2022 08:54 03/10/2022 03/09/2022 09:54 03/10/2022 03/09/2022 10:54 03/10/2022
Obs_data.Timestamp.Format = 'MM/dd/yyyy HH:mm'
Obs_data = 3×3 table
Date Time Timestamp __________ _____ ________________ 03/09/2022 08:54 03/10/2022 00:48 03/09/2022 09:54 03/10/2022 01:48 03/09/2022 10:54 03/10/2022 02:48
.
  댓글 수: 2
Autumn P
Autumn P 2022년 3월 9일
This worked, thank you!
Star Strider
Star Strider 2022년 3월 9일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

David Hill
David Hill 2022년 3월 9일
d=[Obs_data.Date,' ',Obs_data.Time];
datetime(d,'InputFormat','MM/dd/yyyy HH:mm');
  댓글 수: 2
Autumn P
Autumn P 2022년 3월 9일
This did not work for me. I got the following error
Error using datetime/horzcat (line 1387)
Dimensions of arrays being concatenated are not consistent.
David Hill
David Hill 2022년 3월 9일
d=[Obs_data.Date,repmat(' ',size(Obs_data.Date,1),1),Obs_data.Time];%assuming the dates and times are character arrays
%d=[char(Obs_data.Date),repmat(' ',size(Obs_data.Date,1),1),char(Obs_data.Time)];
%use above to convert to char arrays if necessary
datetime(d,'InputFormat','MM/dd/yyyy HH:mm');

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2022년 3월 9일
Why is your Time data stored as a datetime array? IMO it would make more sense for you to import or create it as a duration array.
I don't know how to add yesterday and tomorrow in a way that makes sense but I know how to add right now and 6 hours.
rightNow = datetime('now')
rightNow = datetime
09-Mar-2022 14:45:42
h = hours(6)
h = duration
6 hr
sixHoursFromNow = rightNow + h % datetime + duration = datetime
sixHoursFromNow = datetime
09-Mar-2022 20:45:42
If you're reading your time data as text (say from a file) you can convert that to a duration array pretty easily.
h2 = duration('01:23', 'InputFormat', 'hh:mm')
h2 = duration
01:23:00
anHour23MinutesFromNow = rightNow + h2
anHour23MinutesFromNow = datetime
09-Mar-2022 16:08:42

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by