How to convert hours, minutes, seconds to seconds?

69 次查看(过去 30 天)
Hi,
How can I return an array with
hh:min:sec
into
seconds?
For example
VarName2(1:5)
ans =
'14:54:25'
'14:54:25'
'14:54:25'
'14:54:26'
'14:54:26'
into a array with seconds?

采纳的回答

Daniel
Daniel 2014-10-16
Assuming you mean seconds in the day
% initialize variables
NUM_SECONDS_PER_DAY = 86400.0;
timeStrings = {'14:54:25';'14:54:25';'14:54:25';'14:54:26';'14:54:26'};
% convert times to fractional days using datenum
timeFractionalDays = datenum(timeStrings);
% leave only the part with the most recent day fraction
timeDayFraction = mod(timeFractionalDays,1);
% multiply by number of seconds in a day
timeInSeconds = timeDayFraction .* NUM_SECONDS_PER_DAY
This produces the result
timeInSeconds =
1.0e+04 *
5.3665
5.3665
5.3665
5.3666
5.3666
  8 个评论
Daniel
Daniel 2014-10-16
Simply subtract the first value of the answer vector from itself.
% initialize variables
NUM_SECONDS_PER_DAY = 86400.0;
% convert times to fractional days using datenum
timeFractionalDays = datenum(VarName2);
% leave only the part with the most recent day fraction
timeDayFraction = mod(timeFractionalDays,1);
% multiply by number of seconds in a day
timeInSeconds = timeDayFraction .* NUM_SECONDS_PER_DAY;
% find answer starting from first value
timeInSeconds = timeInSeconds - timeInSeconds(1)

请先登录,再进行评论。

更多回答(1 个)

Stephen23
Stephen23 2023-8-21
编辑:Stephen23 2023-8-21
The approach for MATLAB >=R2014b is to use the DURATION class, e.g.:
C = {'14:54:25'; '14:54:25'; '14:54:25'; '14:54:26'; '14:54:26'};
S = seconds(duration(C))
S = 5×1
53665 53665 53665 53666 53666

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by