spliting date and time strings in a table

7 ビュー (過去 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 Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by