Search code examples
matlabdatedatetime

Convert to datetime array where fractional seconds are only sometimes present?


I have a cell array containing date formatted strings, and I would like to convert the entire array into a datetime array. The problem is that some of the strings contain fractional seconds (with varying degrees of precision), whereas others do not, like this:

my_date_strings{1} = '2022-01-15T14:04:58.23Z'  ;
my_date_strings{2} = '2022-01-15T14:19:28Z'     ;
my_date_strings{3} = '2022-01-08T09:43:24.702Z' ;
my_datetime = datetime(my_date_strings, 'InputFormat','yyyy-MM-dd''T''HH:mm:ss.SS''Z''' );

How can I specify the Input Format for datetime in such a way that it can handle both types? (Ideally, I would like to ignore the fractional seconds on every element, but can it be done using the input format specifier?).


Solution

  • Regexp is hard. erase using a pattern is easier.

    >> x = erase(my_date_strings, "." + digitsPattern)
    x =
      1×3 cell array
        {'2022-01-15T14:04:58Z'}    {'2022-01-15T14:19:28Z'}    {'2022-01-08T09:43:24Z'}
    >> my_datetime = datetime(x, 'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z''' )
    my_datetime = 
      1×3 datetime array
       2022-Jan-15 14:04:58   2022-Jan-15 14:19:28   2022-Jan-08 09:43:24