spliting date and time strings in a table

19 次查看(过去 30 天)
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

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2015-6-26
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 个评论
Stephen23
Stephen23 2015-7-20
编辑:Stephen23 2015-7-20
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')

请先登录,再进行评论。

更多回答(1 个)

Peter Perkins
Peter Perkins 2015-7-6
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 个评论
Zargham Ali
Zargham Ali 2015-7-20
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 . .

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by