MATLAB: How to map an ASCII data file time stamp (with milliseconds) to a variable using the DATENUM function in MATLAB 7.11 (R2010b)

asciidatenumdatevecMATLABmillisecondsstamptime

I want to convert some ASCII data file time stamps to matlab variables using the DATENUM function. I do not wish to change my ASCII data time stamp format which is in the following format:
'2011-06-16 08:29:49'
'2011-06-16 08:29:49.05'
'2011-06-16 08:29:49.1'
Is there a way I can map these time stamps(including milliseconds) to a variable in MATLAB? The variable should be saved in a format that matches the output of the DATENUM function.

Best Answer

Since the ASCII time stamps do not have a consistent format(in terms of milliseconds), you need to to first convert them into a Date Vector using DATEVEC and then use the DATENUM function. The following is a way of doing it:
1) Initially you could use the DATEVEC function (without specifying any input arguments) to create a date vector. DATEVEC converts date and time to a vector of components
dv1 = datevec('2011-06-16 08:29:49');
dv2 = datevec('2011-06-16 08:29:49.05');
dv3 = datevec('2011-06-16 08:29:49.1');
2) To save the data in a variable that matches the output of the DATENUM function, you can then use the DATENUM function (again without any input arguments) to convert the date vectors to a serial date number. The following example refers to the variables 'dv1', 'dv2' and 'dv3' from above:
dn1 = datenum(dv1);
dn2 = datenum(dv2);
dn3 = datenum(dv3);
3) Date vectors have no separate field in which to specify milliseconds. However, the seconds field has a fractional part and accurately keeps the milliseconds field. The following example converts the above variables 'dn1', 'dn2' and 'dn3' to strings using the DATESTR function. Note that MATLAB fully restores the milliseconds count. You do not need to worry about seconds that may or may not have decimal points.
%Date Without Milliseconds
dt1 = datestr(dn1, 'yyyy-mm-dd HH:MM:SS.FFF');
% Date with Two Digit Milliseconds
dt2 = datestr(dn2, 'yyyy-mm-dd HH:MM:SS.FFF');
% Date with One Digit Milliseconds
dt3 = datestr(dn3, 'yyyy-mm-dd HH:MM:SS.FFF');
Displaying 'dt1', 'dt2' and 'dt3' would give you
2011-06-16 08:29:49.000
2011-06-16 08:29:49.050
2011-06-16 08:29:49.100