formulating elapsed time in hours for input data...

1 回表示 (過去 30 日間)
Chris E.
Chris E. 2015 年 6 月 28 日
回答済み: Peter Perkins 2015 年 7 月 6 日
I have some code that I need to change from a string into a vector of numbers representing elapsed hours. My input data looks like:
date_str = '2015-06-05 14:17:36'
'2015-06-05 14:17:36'
'2015-06-05 14:17:36'
'2015-06-05 14:17:36'
'2015-06-05 14:17:36'
'2015-06-05 14:17:39'
'2015-06-05 14:17:39'
'2015-06-05 14:17:39'
'2015-06-05 14:17:39'
'2015-06-05 14:17:39'
'2015-06-05 14:17:39'
'2015-06-05 14:17:40'
'2015-06-05 14:20:09'
'2015-06-05 14:20:09'
'2015-06-05 14:20:09'
'2015-06-05 14:20:09'
'2015-06-05 14:23:00'
'2015-06-05 14:23:00'
'2015-06-05 14:23:34'
'2015-06-05 14:23:34'
'2015-06-05 14:23:35'
'2015-06-05 14:23:35'
'2015-06-05 14:23:35'
'2015-06-05 14:23:35'
'2015-06-05 14:23:35'
'2015-06-05 14:26:47';
This is a rather short list of the data, it is actually made up of over 1000000 date strings, the function I use now is:
function [e_time] = date2time(date_str)
date_format = 'mm/dd/yyyy HH:MM:SS';
t_datevec = zeros(size(date_str,1),6);
e_time = zeros(1,length(date_str));
for i = 1:length(date_str)
t_str = datestr(date_str(i),date_format);
t_datevec(i,:) = datevec(t_str);
e_time(i) = etime(t_datevec(i,:),t_datevec(1,:))/3600;
end
end
So it takes a long time to actually use this function, I'm sure that is due to the for loop, any suggestions or ideas to speed this up? Thank You!

採用された回答

Peter Perkins
Peter Perkins 2015 年 7 月 6 日
In MATLAB R2014b or later, use datetime. With your date_str variable converted to a cell array of strings:
>> d = datetime(cellstr(date_str))
d =
05-Jun-2015 14:17:36
05-Jun-2015 14:17:36
05-Jun-2015 14:17:36
05-Jun-2015 14:17:36
05-Jun-2015 14:17:36
05-Jun-2015 14:17:39
05-Jun-2015 14:17:39
...
05-Jun-2015 14:26:47
>> t1 = d - d(1); t1.Format = 'h' % elapsed since first
t1 =
0 hrs
0 hrs
0 hrs
0 hrs
0 hrs
0.00083333 hrs
0.00083333 hrs
...
0.15306 hrs
>> t2 = diff(d); t2.Format = 'h' % successive diffs
t2 =
0 hrs
0 hrs
0 hrs
0 hrs
0.00083333 hrs
0 hrs
0 hrs
...
0.053333 hrs
Those create durations. If you need double values, wrap the hours function around them. Hope this helps.

その他の回答 (0 件)

カテゴリ

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