Import data into datetime format

2 views (last 30 days)
no
no on 20 Jun 2022
Answered: Steven Lord on 21 Jun 2022
I'm having trouble importing my data into date time format. My data is in an excel format with tens of thousands of rows.
When I use the import data GUI, the second column is not being read in as a datetime. I was able to combine them in excel, but even the combined date and time were returning NaT. Ultimately I want to plot a combined date and time on the x-axis. I'm using 2021b
Thanks.

Answers (2)

Star Strider
Star Strider on 20 Jun 2022
It would help to have the file and the MATLAB release you are using. It would be better to use readtable if you have it. Also, specify how the ‘Date’ variable is formatted, since it is ambiguous (could be 'dd/MM/yyyy' or 'MM/dd/yyyy') as written.
Assuming the second column is being read in as a duration variable:
T1 = table(datetime('8/1/2018','InputFormat','MM/dd/yyyy'),duration('17:42:56.503'),0.4, 0.3, 'VariableNames',{'Date','Time (GMT)','P','S'})
T1 = 1×4 table
Date Time (GMT) P S ___________ __________ ___ ___ 01-Aug-2018 17:42:56 0.4 0.3
T1.DateTime = T1.Date + timeofday(datetime(string(T1.('Time (GMT)'))))
T1 = 1×5 table
Date Time (GMT) P S DateTime ___________ __________ ___ ___ ____________________ 01-Aug-2018 17:42:56 0.4 0.3 01-Aug-2018 17:42:56
.

Steven Lord
Steven Lord on 21 Jun 2022
Consider opening the file in the Import Tool. Using this tool you can interactively adjust how MATLAB imports each column of your data, including telling it to import the data as a datetime or duration array. You can import a few rows of your data, check that it was imported as you want, and modify the settings if it didn't.
If you have multiple files formatted in the same way you could generate a function (click the downward pointing trianle on the Import Selection button) that uses those settings to read in the data then call that function on the rest of the files. Even if you don't have multiple files to read, generating a script or function file could help you learn the various options available for the data import and export functions.

Community Treasure Hunt

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

Start Hunting!