How can I subtract the times without considering the date in question?

12 ビュー (過去 30 日間)
Newbie
Newbie 2021 年 8 月 11 日
コメント済み: Scott MacKenzie 2021 年 8 月 12 日
I have a vector of time which are linked to dates but I only want to subtract the times from each other without considering the dates too. For example, I want to do 4:30 - 3:30 is equal to 1 hour and then 3:30 - 2:50 is equal to 40 minutes (0.6666667) and etc. I dont want Matlab to consider the date period basically.
I have this code for the time from 25-Apr to 01-May but it does take into account the date too:
out1m=24-(seconds(diff(datetime([T_Smooth{2,4};T_Smooth{3,4}])))/3600);
Can anyone help please? Thank you.
  2 件のコメント
Scott MacKenzie
Scott MacKenzie 2021 年 8 月 11 日
Just to clarify... What result do you expect if you subtract 3:30 on April 26 from 4:30 on April 27? 1 hour or 25 hours?
Newbie
Newbie 2021 年 8 月 11 日
1 hour

サインインしてコメントする。

採用された回答

Cris LaPierre
Cris LaPierre 2021 年 8 月 11 日
編集済み: Cris LaPierre 2021 年 8 月 11 日
Use the timeofday function.
% create vector of datetimes
date = datetime(2019,[4;4;5;5],[24;25;1;2],[4;3;2;4],[30;30;50;30],0)
date = 4×1 datetime array
24-Apr-2019 04:30:00 25-Apr-2019 03:30:00 01-May-2019 02:50:00 02-May-2019 04:30:00
% Take difference of the times.
dt = diff(timeofday(date))
dt = 3×1 duration array
-01:00:00 -00:40:00 01:40:00
Use the hours function to turn hh:mm:ss into decimal hours if you want.
hours(dt)
ans = 3×1
-1.0000 -0.6667 1.6667

その他の回答 (1 件)

Scott MacKenzie
Scott MacKenzie 2021 年 8 月 11 日
編集済み: Scott MacKenzie 2021 年 8 月 11 日
Here's one way to do this:
% test data (one month in 30-min increments)
dt = datetime(2021,4,1):minutes(30):datetime(2021,5,1);
% indices of datetime elements to compute hour difference between
n1 = 154;
n2 = 255;
x = datenum(dt(n2) - dt(n1));
hrs = rem(x,1) * 24
hrs = 2.5000
  5 件のコメント
Stephen23
Stephen23 2021 年 8 月 12 日
編集済み: Stephen23 2021 年 8 月 12 日
"what deprecated date functions are you referring to? I only used datetime and minutes in my solution."
You used DATENUM here:
https://www.merriam-webster.com/dictionary/deprecated: "3: to withdraw official support for or discourage the use of (something, such as a software product) in favor of a newer or better alternative."
The DATENUM documentation currently contains this note:
Scott MacKenzie
Scott MacKenzie 2021 年 8 月 12 日
Oops, yes, I used datenum as well. Thanks for pointing that out. The language to discourage use of this function could be a tad stronger, however. Below is what appears for xlsread, as an example.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by