merging date and time

25 次查看(过去 30 天)
Nicole Palermo
Nicole Palermo 2018-6-7
评论: Sreeraj T 2025-6-16
Hello!
I have a table with date (mm/dd/yyyy) in one column in and time(matlab serial number for hh:mm:ss) in the other. I want to create a new column within the same table or outside of it that combines them into one column, into the form mm/dd/yyyy hh:mm:ss. Can this be done?
Thank you!

回答(1 个)

Paolo
Paolo 2018-6-7
Nicole, the following example should help you in what you are trying to do. I have added some comments in the code to help you. To perform arithmetic operations on dates and times, you must ensure that they have the same format as shown below.
It initially creates a table which looks like this:
dates times
__________ __________
09/29/2017 7.3706e+05
09/28/2017 7.3706e+05
09/27/2017 7.3706e+05
as you indicated that you have dates in the first column and datenums in the second column.
%First column of table with dates.
DateStrings = {'29/09/2017','28/09/2017','27/09/2017'};
dates = datetime(DateStrings,'Format','MM/dd/yyyy')';
%Second column of table with times in datenum format.
TimeStrings = {'20:30:30','19:30:21','14:32:01'};
times = datenum(TimeStrings);
%This will create the table as shown in the first part of the answer.
t = table(dates,times);
%Format both columns to MM/dd/yyyy HH:mm:SS for addition.
dates = datetime(t.dates,'Format','MM/dd/yyyy HH:mm:SS');
times = datetime(t.times,'ConvertFrom','datenum','Format','MM/dd/yyyy HH:mm:SS');
%Add dates to times.
fullt = dates+timeofday(times);
t.DatesNTimes = fullt;
The final table contains the third additional column which is the result of the addition of the date of the first and the time of the second.
dates times DatesNTimes
__________ __________ ___________________
09/29/2017 7.3706e+05 09/29/2017 20:30:00
09/28/2017 7.3706e+05 09/28/2017 19:30:00
09/27/2017 7.3706e+05 09/27/2017 14:32:00
  11 个评论
Stephen23
Stephen23 2025-6-13
编辑:Stephen23 2025-6-13
@Sreeraj T: The conversion to DATENUM is superfluous. The conversion of serial date numbers to DATETIME is most likely superfluous. There is no point in setting the FORMAT of TIMES.
date_var = {'29-09-2025';'28-09-2025';'27-09-2025'};
time_var = {'13:55:06';'13:55:07';'13:55:08'};
Dates = datetime(date_var,"InputFormat","dd-MM-uuuu","Format","dd-MM-uuuu HH:mm:ss.SSS");
Times = duration(time_var);
DateTimeVar = Dates+Times
DateTimeVar = 3×1 datetime array
29-09-2025 13:55:06.000 28-09-2025 13:55:07.000 27-09-2025 13:55:08.000
Selecting the best approach depends on your input data, which you have not provided or described.
Sreeraj T
Sreeraj T 2025-6-16

@Stephen23, Thank you for the clarification and sorry for the delay.

Just to clarify: yes, I haven't given the data explicitly, but I have given it's structure.

Thanks again.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by