Search code examples
matlabdatedatetimemilliseconds

How to convert datestring with milliseconds in datetime matlab


Hi I have a small problem with the datestring. My data is in a matlab table with about 2 million rows. The time comes in the format DateStrings='2014-06-23T17:06:41.584+0200'. I would like to have it in datenum . So I thought I can convert it to datetime using the following code and then convert it to datenum.

    t = datetime(DateStrings,'InputFormat','uuuu-MM-dd''T''HH:mm:SSSSSXXX','TimeZone','UTC');

however this does not work. With the same error message"Unable to parse date/time string using the format 'uuuu-MM-dd'T'HH:mm:SSSSSXXX'. I tried for a few strings to remove the miliseconds and then to code works. I dont really need the milliseconds so I was thinking to split the string and remove the milliseconds. However there comes the problem with the amount of data and I run into memory problems. Does anybody know how to do this in a smart way. kind regards Matthias


Solution

  • Some of your formatting for datetime is incorrect.

    Tweaked slightly:

    DateStrings='2014-06-23T17:06:41.584+0200';  
    t = datetime(DateStrings,'InputFormat','uuuu-MM-dd''T''HH:mm:ss.SSSXXXX','TimeZone','UTC');
    

    Which returns:

    t = 
    
       23-Jun-2014 15:06:41
    

    EDIT:

    Forgot about the second part of the question. To use datenum you'll again have to change the syntax slightly. I will also note that you can do this conversion on your strings without having to convert to a datetime array.

    For example:

    DateStrings='2014-06-23T17:06:41.584+0200';
    t = datenum(DateStrings, 'yyyy-mm-ddTHH:MM:SS.FFF');
    test = datestr(t, 'yyyy-mm-dd HH:MM:SS.FFF');
    

    Which returns:

    t =
    
       7.3577e+05
    

    and

    test =
    
    2014-06-23 17:06:41.584
    

    A final note on datenum is that there is no support for timezones. Since datenum represents the number of days from a fixed date we can add/remove hours simply:

    DateStrings='2014-06-23T17:06:41.584+0200';
    t = datenum(DateStrings, 'yyyy-mm-ddTHH:MM:SS.FFF');
    
    hourstoshift = -2;
    t = datenum(t + hourstoshift/24);
    test = datestr(t, 'yyyy-mm-dd HH:MM:SS.FFF')
    

    Which returns:

    test =
    
    2014-06-23 15:06:41.584
    

    Here I've specified the hours to shift manually, but you could also parse your time and determine this automatically.