Using datenum on a cell array with different date formats

1 vue (au cours des 30 derniers jours)
Jonathan
Jonathan le 19 Nov 2012
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.

Réponse acceptée

José-Luis
José-Luis le 19 Nov 2012
Modifié(e) : José-Luis le 19 Nov 2012
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 commentaire
Jonathan
Jonathan le 20 Nov 2012
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!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Time Series Objects dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by