How can I subtract the times without considering the date in question?
41 views (last 30 days)
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:
Can anyone help please? Thank you.
Cris LaPierre on 11 Aug 2021
Edited: Cris LaPierre on 11 Aug 2021
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)
% Take difference of the times.
dt = diff(timeofday(date))
Use the hours function to turn hh:mm:ss into decimal hours if you want.
More Answers (1)
Scott MacKenzie on 11 Aug 2021
Edited: Scott MacKenzie on 11 Aug 2021
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