How to represent fractional part of a second in Matlab time series object?

I want to represent time in a time series object in matlab in the following format. dd-mmm-yyyy HH: MM: SS.FFF. I converted the date to the format of the desired date, but when I create a time series object, then the fraction of the second is rounded to the nearest integer, as a result I get a redundant time value.

What do I need to do to get the time series with millisecond precision?

I use:

dateStr = datestr(dateNum, 'dd-ddd-yyyy HH:MM:SS.FFF')

      

to convert it to a date string.

01-Mar-2008 18:28:51.810

      

But, when I use this in time series, the fractional part of the second is rounded as shown below.

tsobject = timeseries( x, dateStr, 'name', 'X-ord')
01-Mar-2008 18:28:52

      

Actual date string

01-Mar-2008 18:28:51.810
01-Mar-2008 18:29:05.646
01-Mar-2008 18:29:07.376
01-Mar-2008 18:29:09.105
01-Mar-2008 18:29:10.835

      

Using data instead of datestr

tsobject = timeseries( x, dateNum, 'name', 'X-ord')
tsobject.TimeInfo
tsdata.timemetadata
Package: tsdata

  Non-Uniform Time:
    Length       90419

  Time Range:
    Start        7.334688e+05 seconds
    End          7.336596e+05 seconds

  Common Properties:
     Units: 'seconds'
     Format: ''
     StartDate: ''

      

+3


source to share


1 answer


This should get the job done (especially in R2014a and earlier ):

str = '12-Apr-2015 11:22:23.123';
num = datenum(str,'dd-mmm-yyyy HH:MM:SS.FFF');  % string -> serial
str = datestr(num,'dd-mmm-yyyy HH:MM:SS.FFF');  % serial -> string

      

Since R2014b there is a better implementation for time / date data. Therefore you can use the datetime

-object.

str = '12-Apr-2015 11:22:23.123';
obj = datetime(str,'InputFormat','dd-MMM-yyyy hh:mm:ss.SSS');
obj.Format = 'dd-MMM-yyyy hh:mm:ss.SSS';

      



With timeseries

-objects,
you need to enter a serialized date (in this case a variable num

), since there is no valid input format for strings with milliseconds for timeseries

-objects.

% your strings
dateStr = ['01-Mar-2008 18:28:51.810';
           '01-Mar-2008 18:29:05.646';
           '01-Mar-2008 18:29:07.376';
           '01-Mar-2008 18:29:09.105';
           '01-Mar-2008 18:29:10.835'];

% string -> serial
dateNum = datenum(dateStr,'dd-mmm-yyyy HH:MM:SS.FFF');  % string -> serial

% serial -> string (uncomment to see if the serialized version is ok
%dateStr2 = datestr(dateNum,'dd-mmm-yyyy HH:MM:SS.FFF');  

% generate sample data
x = ones(length(dateNum),1);

% create timeseries-object
tsobject = timeseries(x, dateNum, 'name', 'X-ord');

% display time in timeseries-object with defined format
datestr(tsobject.Time(:),'dd-mmm-yyyy HH:MM:SS.FFF')

      

This returns:

ans =
01-Mar-2008 18:28:51.810
01-Mar-2008 18:29:05.646
01-Mar-2008 18:29:07.376
01-Mar-2008 18:29:09.105
01-Mar-2008 18:29:10.835

      

+2


source







All Articles