计算时间戳的差异

时间:2018-02-12 06:27:25

标签: matlab datetime time timestamp duration

我想计算前一行的时差,但结果与预期不符。例如,deltatime(2,5)(请参阅第一个屏幕截图)中的结果应为3而不是1317:47-17:44)。

enter image description here enter image description here

我的代码:

% Calculate connection time
sizedate = length(date);

for i=2:sizedate
 X=char(date(i));
 X=[X(1) X(2)];

 if(X=='18')
   timenum_on=char(time(i));
   timenum_b4=char(time(i-1));
     if(timenum_on(5)<timenum_b4(5) || timenum_on(1) >=timenum_b4(1)
        timenum_on(5)=timenum_on(5)+10;
        timenum_on(4)=timenum_on(4)-1;
        deltatime(i,")=timenum_on-timenum_b4;
     else
        timenum_b4(5)=10-timenum_b4(5);
        deltatime(i,:)=timenum_on-timenum_b4;
     end

2 个答案:

答案 0 :(得分:1)

为什么不直接将datetime个对象直接减去/差异来获取duration个对象?这是一个演示:

function out = q48740661
dt = datetime(2017, 02, 12, 17, 43 + (0:4).^2, 12).';
out = flipud(diff(flipud(dt)));

ans = 

  4×1 duration array

   -0:01:00
   -0:03:00
   -0:05:00
   -0:07:00

答案 1 :(得分:0)

尝试创建此功能:

deltatime=func_time(time);

此功能的内容:

function time_diff= func_time(time_arr)
n=size(time_arr(:,1));
y=n(1);
time_diff=zeros(n,n);
for i=1:y
    for j=1:y
        time_1=time_arr(i,:); %char array of first time
        time_2=time_arr(j,:); %char array of second time
        time_cell=time_1;
        ctr=1;
        for k=1:size(time_1(:)+1)
            if(time_1(k)==':')
                av=str2num(time_1(ctr:(k-1)));
                bv=str2num(time_2(ctr:(k-1)));
                time_cell(ctr:(k-1))=int2str(av-bv)
                ctr=k+1
            end
            if(k==5)
                av=str2num(time_1(ctr:(k)));
                bv=str2num(time_2(ctr:(k)));
                time_cell(ctr:k)=int2str(av-bv)
            end
        end
        time_diff(i,j)=time_cell();
    end
end
  

我假设deltatime(i,j)time(i)-time(j)