Need help subtracting and doing if statements for time

I would like to subtract two different times in the HH:MM format from an excel sheet and to then use result to use in a if statement where I will compare the resultant time from the substraction to another period of time, lets say 30 minutes.

 Accepted Answer

There doesn't seem to be any date information included with your data, so I'd use duration instead of datetime. I'm mostly using your data but I also wanted to show how I'd handle midnight crossings.
du = duration(["6:30", "7:30"; "8:30", "9:30"; "9:00", "10:00"; "17:45", "1:00"], ...
'InputFormat', 'hh:mm')
du = 4×2 duration array
06:30:00 07:30:00 08:30:00 09:30:00 09:00:00 10:00:00 17:45:00 01:00:00
difference = du(:, 2)-du(:, 1)
difference = 4×1 duration array
01:00:00 01:00:00 01:00:00 -16:45:00
In this case the last difference is negative, which suggests that the flight was in the air at midnight. So let's add 24 hours to that entry.
inAirAtMidnight = difference < hours(0)
inAirAtMidnight = 4×1 logical array
0 0 0 1
difference(inAirAtMidnight) = difference(inAirAtMidnight) + hours(24)
difference = 4×1 duration array
01:00:00 01:00:00 01:00:00 07:15:00
Note that I was able to use < between the duration array difference and the duration array returned by hours(0) to perform some comparisons.
Alternately we could have modified du directly. I made a copy of du as du2 in case you wanted to run the code and experiment yourself.
du2 = du;
departure = du2(:, 1);
arrival = du2(:, 2);
arrivedBeforeDeparture = arrival < departure
arrivedBeforeDeparture = 4×1 logical array
0 0 0 1
du2(arrivedBeforeDeparture, 2) = du2(arrivedBeforeDeparture, 2) + hours(24)
du2 = 4×2 duration array
06:30:00 07:30:00 08:30:00 09:30:00 09:00:00 10:00:00 17:45:00 25:00:00
difference2 = diff(du2, [], 2)
difference2 = 4×1 duration array
01:00:00 01:00:00 01:00:00 07:15:00

1 Comment

I was trying for 2 hours and this instantly worked, thank you very much!

Sign in to comment.

More Answers (0)

Products

Release

R2021a

Community Treasure Hunt

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

Start Hunting!