MATLAB: Datetime with variable format

datetime

I have an output file that has timestamps in the form of 'yyyy-MM-dd HH:mm:ss.S' or 'yyyy-MM-dd HH:mm:ss'. I would like a clean way to convert them from date strings into an array of date time format.
Example code:
a={'2016-02-09 10:28:00';'2016-02-09 10:28:01.5'}
out=datetime(a,'InputFormat','yyyy-MM-dd HH:mm:ss.S','InputFormat','yyyy-MM-dd HH:mm:ss','Format','yyyy-MM-dd HH:mm:ss.S');
Actual output:
out =
2016-02-09 10:28:00.0
NaT
Desired output:
out =
2016-02-09 10:28:00.0
2016-02-09 10:28:00.5

Best Answer

Unfortunatelly you cannot specify multiple InputFormats simultaneously. Common to Name-Value pairs is that the last instance of a name value pair is used; in your example this is: 'yyyy-MM-dd HH:mm:ss'. One thing you can do to work around this issue is to convert the cell string to a vector of MATALB Serial Date Numbers and then to a datetime:
d = datenum(a);
d = datetime(d,'Format','yyyy-MM-dd HH:mm:ss.S','convertFrom','datenum');
I would caution you here as if you attempt to change the format in the line d = datenum(a) you will error due to a non-conforming entry.