Using datenum on a cell array with different date formats

조회 수: 1 (최근 30일)
Jonathan
Jonathan 2012년 11월 19일
I have a cell array with dates stored with two different formats, and want to convert this array to a column vector containing the numerical date value.
myDates = {'31.12.2009 23:58:31'; '25.12.2009'; '15.12.2009 15:18:10'};
This should return the following values: 7.341389989699074e+005, 734132, 7.341226376157408e+005
The two different formats are 'dd.mm.yyyy HH:MM:SS' and 'dd.mm.yyyy'. Calling datenum and specifying the wrong format causes an exception. Now, let's say myDates is really long. I could use a for loop with try/catch to go through myDates and try first with the long date format and then try with the shorter, but this takes a lot of time compared to just use datenum on the entire array at once. Is there a way I can tell datenum to try another format if the first one fails, or maybe go through the array in some efficient way and make all the dates the same format? Thank you in advance.

채택된 답변

José-Luis
José-Luis 2012년 11월 19일
편집: José-Luis 2012년 11월 19일
myDates = {'31.12.2009 23:58:31'; '25.12.2009'; '15.12.2009 15:18:10'};
idx = cellfun(@(x) isempty(regexp(x,':')),myDates);
myDates(idx) = cellfun(@(x) {[x ' 00:00:00']},myDates(idx));
your_vals = cellfun(@(x) datenum(x,'dd.mm.yyyy HH:MM:SS'),myDates);
  댓글 수: 1
Jonathan
Jonathan 2012년 11월 20일
Thank you! Can confirm that it works. However, it is not very efficient. It is the last line in your code there that uses a lot of resources, is is better to use datenum directly like this:
myDates = {'31.12.2009 23:58:31'; '25.12.2009'; '15.12.2009 15:18:10'};
idx = cellfun(@(x) isempty(regexp(x,':')),myDates);
myDates(idx) = cellfun(@(x) {[x ' 00:00:00']},myDates(idx));
your_vals = datenum(myDates,'dd.mm.yyyy HH:MM:SS');
Now I have learned about anonymous functions as well ;) Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Time Series Objects에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by