merging date and time

87 views (last 30 days)
Nicole Palermo
Nicole Palermo on 7 Jun 2018
Commented: Peter Perkins on 5 Jun 2019
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!

Answers (1)

Paolo
Paolo on 7 Jun 2018
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 Comments
Louis Keiner
Louis Keiner on 31 May 2019
Thank you! This has helped a lot.
Peter Perkins
Peter Perkins on 5 Jun 2019
Paola, timeofday is a function that accepts a datetime and returns a duration. There's no reason to call it on a duration.

Sign in to comment.

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!