merging date and time

63 次查看(过去 30 天)
Nicole Palermo
Nicole Palermo 2018-6-7
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
  6 个评论
Louis Keiner
Louis Keiner 2019-5-31
Thank you! This has helped a lot.
Peter Perkins
Peter Perkins 2019-6-5
Paola, timeofday is a function that accepts a datetime and returns a duration. There's no reason to call it on a duration.

请先登录,再进行评论。

类别

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