Using datenum on a cell array with different date formats

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