필터 지우기
필터 지우기

Need help subtracting and doing if statements for time

조회 수: 3 (최근 30일)
Yassin Wahby
Yassin Wahby 2024년 3월 15일
댓글: Yassin Wahby 2024년 3월 15일
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.

채택된 답변

Steven Lord
Steven Lord 2024년 3월 15일
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
Yassin Wahby
Yassin Wahby 2024년 3월 15일
I was trying for 2 hours and this instantly worked, thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by