Matlab:计算小数秒内日期时间数组之间的差异

时间:2015-05-19 23:54:18

标签: matlab datetime

我用小数精度(百分之几秒)读取时间数据:

对于此datetime数组中的每个条目,我想确定与第一个条目的差异,以秒为单位(具有小数精度):

times=datetime(myCellArray,'InputFormat','HH:mm:ss.SS');
eventtimes=between(starttime,times(2:end));

返回:

eventtimes = 

0h 0m 19.72s
0h 1m 46s
0h 6m 45.9s
0h 6m 53.18s

我想从这里得到一个简单的持有(小数)秒的常规数组:

[19.72
106
405.9
413.18]

到目前为止我所尝试的(分裂,时间),结果总是失去分数。

3 个答案:

答案 0 :(得分:0)

假设eventtimes是字符串的单元格数组,您可以这样做:

eventtimes={'0h 0m 19.72s'
    '0h 1m 46s'
    '0h 6m 45.9s'
    '0h 6m 53.18s'};

for i=1:length(eventtimes)
    %// Read each line of data individually
    M(i,:)=sscanf(eventtimes{i},'%d%*s%d%*s%f%*s').';
end

s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds

给出了

s =
   19.7200
  106.0000
  405.9000
  413.1800

答案 1 :(得分:0)

关于@David提供的答案,最后一行代码:

s=(M(:,1)*24+M(:,2))*60+M(:,3) %// Convert into seconds

应该是:

s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds

由于M(:,1)包含hours,要将它们转换为秒,它们必须乘以3600 (60 min. * 60 sec.)

问题中描述的预期结果和@David提供的结果似乎只是因为所有输入都有" 0h"。

如果任何输入时间持续超过1小时,结果将为:

0h 0m 19.72s
2h 1m 46s
3h 6m 45.9s
0h 6m 53.18s

s=
   19.72
 7306.00
11205.90
  413.18

希望这有帮助。

答案 2 :(得分:0)

我找到了一个使用etime的解决方案,绕过了“between”函数和奇怪的calendarDuration类型输出:

%read in with fractions
times=datetime(myCellArray(:,1),'InputFormat','HH:mm:ss.SS');

%turn into datevectors (uses today's date: works as long as midnight isn't crossed)
timevect=datevec(times);

%separate start time from subsequent times
starttime=timevect(1,:);
othertimes=timevect(2:end,:);

%use etime with repmat of starttime to get differences:
relativetimes=etime(othertimes,repmat(starttime,[size(othertimes,1) 1]));

relativetimes(1:4)

ans =

                 19.72
                   106
                 405.9
                413.18