I have csv file with a column containing the date and time combined as seen below.
How do I separate the date and time?
10/31/2017 17:27:56
10/31/2017 17:27:59
10/31/2017 17:28 :03

 Réponse acceptée

Cris LaPierre
Cris LaPierre le 29 Déc 2018
Modifié(e) : Cris LaPierre le 29 Déc 2018

0 votes

How are you currently reading it in? What does your other data look like? There is a space between then, so as long as it doesn't mess up your other data, you could use a space and a comma as delimiters.
Do you need it separate? What if you read it in as a datetime? I'd be tempted to use readtable and just keep it all together, but I don't know what your application is.

5 commentaires

je
je le 29 Déc 2018
My csv file has three main columns: Longitude, Latitude, Date/Time.
I am able to read the Longitude and Latitude using xlsread command once I call out the filename.
The date and time are combined together and exactly as: 10/9/2017 12:19:06 PM. All I would like to do is to split the date and the time. I need it split into two different columns as I will be needing to find the time difference bewteen gps locations
Cris LaPierre
Cris LaPierre le 29 Déc 2018
You can take a time difference of a datetime. Just saying...
Here are two ways to do it. Not necessary to go beyond readtable, as you can take the time difference of a datetime.
opts = detectImportOptions('testData.csv');
opts = setvartype(opts,1,'datetime');
opts = setvaropts(opts,1,'DatetimeFormat','MM/dd/yyyy HH:mm:ss');
data = readtable('testData.csv',opts);
% Truly split out date and time
[y m d] = ymd(data.Var1);
[h m s] = hms(data.Var1);
data.date = datetime(y,m,d);
data.time = datetime(h,m,s);
% Disply date and time (though full info is in both)
data.date2 = data.Var1;
data.date2.Format = 'MM/dd/yyyy';
data.time2 = data.Var1;
data.time2.Format = 'HH:mm:ss';
I made a dummy csv file for this:
10/31/2017 17:27:56 36.823354 -83.248541
10/31/2017 17:27:59 41.718847 -100.818924
10/31/2017 17:28:03 24.782741 -100.818924
Greg LANGE
Greg LANGE le 10 Sep 2022
int the dummy csv file the info are separed with "," or ";".
The colonn "36.823354" and "-83.248541" are not used right ? just to show that the code read only the first colonn the do the job ?
Cris LaPierre
Cris LaPierre le 10 Sep 2022
Modifié(e) : Cris LaPierre le 10 Sep 2022
The data in testData.csv are separated by commas:
10/31/2017 17:27:56,36.823354,-83.248541
10/31/2017 17:27:59,41.718847,-100.818924
10/31/2017 17:28:03,24.782741,-100.818924
However, you can specify different/multiple delimiters as needed. See here: https://www.mathworks.com/help/matlab/ref/readtable.html#mw_de8dba79-6cba-4cea-924b-516d8873a6e3

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by