spliting date and time strings in a table

18 vues (au cours des 30 derniers jours)
stephen
stephen le 26 Juin 2015
Modifié(e) : Stephen23 le 20 Juil 2015
I am importing data from a large csv into a table. One column in the csv is a string of dates and times. I want to split this column so that each has its own column and variable in the table. I have tried adding multiple delimiters but readtable does not seem to be able to handle this. Now, I am trying to read the table in as is then split the date and time using a for loop. The date and time are separated by a blank space.
N = size(x,1);
x.Date = cell(N,1);
x.Time = cell(N,1);
for n = 1:N
x.Date{n} = x.DateTime{n}(1:strfind(x.DateTime{n},' ')-1);
x.Time{n} = x.DateTime{n}(strfind(x.DateTime{n},' ')+1:end);
end
However, this takes a really long time as N can be large. Is there a better and quicker way to do this?
Thanks

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 26 Juin 2015
data={'23/06/2015 00:50:12';'24/06/2015 12:30:45';'25/06/2015 13:00:01'}
a=datevec(data,'dd/mm/yyyy HH:MM:SS')
date=datestr(datenum(a),'dd/mm/yyyy')
time=datestr(datenum(a),'HH:MM:SS')
  2 commentaires
stephen
stephen le 26 Juin 2015
Worked great. Thanks.
Stephen23
Stephen23 le 20 Juil 2015
Modifié(e) : Stephen23 le 20 Juil 2015
One can also convert directly to serial date numbers:
a = datenum(data,'dd/mm/yyyy HH:MM:SS')
date = datestr(a,'dd/mm/yyyy')
time = datestr(a,'HH:MM:SS')

Connectez-vous pour commenter.

Plus de réponses (1)

Peter Perkins
Peter Perkins le 6 Juil 2015
If all you want is strings, Azzi's answer works. But you may find the following more useful. Given this file:
timestamp,x
23-Jun-2015 00:50:12,-0.43359
24-Jun-2015 12:30:45,0.34262
25-Jun-2015 13:00:01,3.5784
The following creates a table with a datetime variable for the date, and a duration for the time:
>> readtable('myfile.csv','Format','%D%f');
>> t.date = dateshift(t.timestamp,'start','day');
>> t.date.Format = 'dd-MMM-yyyy';
>> t.time = timeofday(t.timestamp);
>> t.timestamp = []
t =
x date time
_______ ___________ ________
2.7694 23-Jun-2015 00:50:12
-1.3499 24-Jun-2015 12:30:45
3.0349 25-Jun-2015 13:00:01
  1 commentaire
Zargham Ali
Zargham Ali le 20 Juil 2015
hi i want to add a string of date and time in the first column of excel file. With start and end date and time shown 24 hourly for one day. i would be grateful for your help. Format is below 01/01/2015 00:00;
01/01/2015 01:00; . 01/01/2015 24:00 . 02/01/2015 00:00 . . 02/01/2015 01:00 . .

Connectez-vous pour commenter.

Catégories

En savoir plus sur Dates and Time dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by