开发者

Dealing with date strings with different formats in Matlab

开发者 https://www.devze.com 2023-02-12 12:55 出处:网络
I have a very long vector of date strings (1000000+) in Matlab that I want to convert to a serial number format. The issue is that not every date string is the same format. They are one of two formats

I have a very long vector of date strings (1000000+) in Matlab that I want to convert to a serial number format. The issue is that not every date string is the same format. They are one of two formats,

'2010-03-04 12:00:00.1'

or

'2010-03-04 12:00:00'

The problem is that not all the strings have the millisecond precision. There is no regular pattern as to where these strings without milliseconds occur. The data is originally read from a data file, and the strings currently exist as cell arrays. My work around this is as follows:

for i=1:leng开发者_开发问答th(dates),
    if length(dates{i})==19
        dates(i)=datenum(temp);
    elseif length(dates{i})==21
        dates(i)=datenum(temp,'yyyy-mm-dd HH:MM:SS.FFF');
    end
end

Is there perhaps a better way to go about this? It is important that I retain the millisecond precision when it is present. The intent of this is that I will have to extract and calculate statistics on data associated with each time based on different time criteria, and I figured it would be easier if the dates were handled as numbers.


In MATLAB R2010b, I'm able to get the desired output when calling DATENUM with no additional formatting arguments:

>> dateStrs = {'2010-03-04 12:00:00.1'; ...  %# Sample strings
               '2010-03-04 12:00:00'};
>> datenum(dateStrs)

ans =

  1.0e+005 *

    7.3420            %# The same? No, the Command Window just isn't displaying 
    7.3420            %#   many places after the decimal point.

>> format long        %# Let's make it show more decimal places
>> datenum(dateStrs)

ans =

  1.0e+005 *

   7.342015000011574  %# And there's the difference!
   7.342015000000000
0

精彩评论

暂无评论...
验证码 换一张
取 消