How to convert date/time from excel in 2 separate columns to a single date/time variable in matlab
4 views (last 30 days)
Show older comments
I have a long data spreadsheet in excel which has date in 1 column and time in a separate column.
Example:
Date 08/09/2018
Time 04:12:32
I would like to convert each date/time pair into a single value representing the date and time, so that I can follow the exact times of other variables from this excel spreadsheet.
Is there a way to do this?
0 Comments
Answers (3)
Star Strider
on 30 Oct 2018
One option:
dn = [datenum({'08/09/2018'; '08/10/2018'}, 'mm/dd/yyyy') + rem(datenum({'04:12:32'; '04:12:35'}, 'HH:MM:SS'),1)];
dt = datetime(dn, 'ConvertFrom','datenum')
dt =
09-Aug-2018 04:12:32
10-Aug-2018 04:12:35
0 Comments
Peter Perkins
on 31 Oct 2018
The right answer depends on how they are stored in the spreadsheet and what version of MATLAB you are using.
In recent versions, assuming they are stored appropriately in the spreadsheet, readtable should create a table with a datetime variable for the dates, and a duration variable for the times. Just add those two together and create a new variable in the table.
Otherwise, you may end up with text, or numbers that you will need to convert. Mostly that's easy, unless you end up with text for the times in an older version of MATLAB. For that, use text2duration on the FEX.
0 Comments
Michael Wolf
on 1 Nov 2018
1 Comment
Peter Perkins
on 1 Nov 2018
You have left out a crucial step in either your description, or your code. Excel counts days from 1900. datestr uses MATL:AB's (old) convention of counting days since 0.
Unless you are using a pretty old version of MATLAB, use readtable. Then follow my previous advice to use datetimes, not datenums. If what you find yourself with is a set of Excel serial date numbers, there is a very easy conversion to datetime, see 'ConvertFrom' in the doc.
See Also
Categories
Find more on Spreadsheets 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!