Search code examples
matlabmatlab-figurematlab-deploymentmatlab-compiler

Calculate the elapsed time in seconds from date with 'HH:MM:SS' format ( MATLAB)


I'm trying to convert date in a string a vector of time, which as this format: 'HH:MM:SS', in a vector of time in seconds.It works well till a certain point and after it returns fake values.

Here is what I'm doing:

a={'596:30:18';'596:30:28';'596:30:38';'596:30:48';'596:30:58';'596:31:08';'596:31:18';'596:31:28';'596:31:38';'596:31:48';'596:31:58';'596:32:08';'596:32:18';'596:32:28';'596:32:38';'596:32:48';'596:32:58';'596:33:08'};

         formatIn = 'HH:MM:SS';
         DateVector = datevec(a(1:end,:),formatIn);
         time = etime(DateVector,DateVector(1,:));    

It returns:

DateVector =

2017    1   25  20  30  18
2017    1   25  20  30  28
2017    1   25  20  30  38
2017    1   25  20  30  48
2017    1   25  20  30  58
2017    1   25  20  31  8
2017    1   25  20  31  18
2016    12  7   3   28  40,7040000000000
2016    12  7   3   28  50,7040000000000
2016    12  7   3   29  0,704000000000000
2016    12  7   3   29  10,7040000000000
2016    12  7   3   29  20,7040000000000
2016    12  7   3   29  30,7040000000000
2016    12  7   3   29  40,7040000000000
2016    12  7   3   29  50,7040000000000
2016    12  7   3   30  0,704000000000000
2016    12  7   3   30  10,7040000000000
2016    12  7   3   30  20,7040000000000

and

time =

0
10
20
30
40
50
60
-4294897,29600000
-4294887,29600000
-4294877,29600000
-4294867,29600000
-4294857,29600000
-4294847,29600000
-4294837,29600000
-4294827,29600000
-4294817,29600000
-4294807,29600000
-4294797,29600000

only the 7 firt value are correct. Anybody knows why is this happening?


Solution

  • here is another way without loops and way faster (in theory):

    B = regexp(a, ':', 'split');
    C = vertcat(B{:});
    D = str2double(C);  %D = cellfun(@str2num, C); also works but slower
    

    this translates your time stamps to Hours:Minutes:Seconds in 3 columns, you can then quite easily subtract and get the time:

    E =  bsxfun(@minus,D,D(1,:));
    F = E(:,1)*3600 + E(:,2)*60 + E(:,3)
    
    >>F =
    
     0
    10
    20
    30
    40
    50
    60
    70
    80
    90
    100
    110
    120
    130
    140
    150
    160
    170
    

    btw, what a strange datetime format.