4
votes

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

What I should do so get time series to the precision of millisecond?

I am using:

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

to convert it into date string.

01-Mar-2008 18:28:51.810

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

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

Actual date string is

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 datenum 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: ''
1
Use another time format I guess.Ander Biguri

1 Answers

3
votes

This should do the job (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

Starting from R2014b there is a better implementation for time/date-data. Therefore you can use a 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 have to input the serialized date (in this case variable num), because 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