[英]Is there a Matlab function to convert elapsed seconds to HH:MM:SS format?
[英]Calculate the elapsed time in seconds from date with 'HH:MM:SS' format ( MATLAB)
我正在嘗試將字符串中的日期轉換為時間的向量,其格式為:'HH:MM:SS',以秒為單位的時間向量,它可以很好地工作到特定點並返回假值。
這是我在做什么:
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,:));
它返回:
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
和
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
只有第7點火值正確。 有人知道為什么會這樣嗎?
這是另一種沒有循環且更快的方法(理論上):
B = regexp(a, ':', 'split');
C = vertcat(B{:});
D = str2double(C); %D = cellfun(@str2num, C); also works but slower
這會將您的時間戳記轉換為Hours:Minutes:Seconds in 3 column,然后您可以輕松地減去並獲得時間:
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
順便說一句,多么奇怪的日期時間格式。
我能想到的唯一解釋是, HH
標識符不打算與3位數字的小時一起使用。 實際上datevec的datevec文檔說
HH-小時,兩位數格式
因此,也許'596:30:28'
不是有效的日期字符串,您需要將其轉換為其他格式,例如'dd:HH:MM:SS'
。
可以這樣進行(假設所有小時都是3位數字):
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'};
a_ddhhmmss = {};
for ii=1:length(a)
datestring = a{ii};
colon_indices = strfind(datestring, ':'); %check how many digits the hours have
hours_digits = colon_indices(1)-1;
hours = str2num(datestring(1:hours_digits));
days = floor(hours/24) + 1; % start with day=1
hours = rem(hours,24);
a_ddhhmmss{end+1} = [num2str(days), ':', num2str(hours), datestring(4:end)];
end
formatIn = 'dd:HH:MM:SS';
DateVector = datevec(a_ddhhmmss(1:end,:),formatIn)
time = etime(DateVector,DateVector(1,:))
當然,您觀察到的行為只是在日期'596:30:18'
和'596:30:28'
之間設置仍然沒有意義。 即使使用datevec
函數超出范圍,它也應該拋出錯誤而不是返回無意義的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.