spliting date and time strings in a table

조회 수: 5 (최근 30일)
stephen
stephen 2015년 6월 26일
편집: Stephen23 2015년 7월 20일
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
stephen
stephen 2015년 6월 26일
Worked great. Thanks.
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에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by