필터 지우기
필터 지우기

Datetime differences but ignoring years

조회 수: 10 (최근 30일)
Dan Houck
Dan Houck 2023년 4월 4일
댓글: Peter Perkins 2023년 4월 5일
I have a bunch of datetimes and I want to know the times between them, but I don't want to consider the year. So, say the dates are:
2019-11-29 09:00:00
2020-11-20 10:10:00
2021-11-22 08:30:00
The order I want to sort these into when ignoring the year would be:
11-20 10:00:00
11-22 08:30:00
11-29 09:00:00
Then I want the time between these in minutes, so [2790,10110] if I did my math right. What's the easiest way to do this?

채택된 답변

Cris LaPierre
Cris LaPierre 2023년 4월 4일
You can't just drop the year from a datetime variable. It's there, even if your viewing format does not display it. To me, that suggests either making the year the same in all of your datetimes, or sort by month of year, then day of month, then hour, etc.
I think changing the year is easiest, especially since your minutes are calculated ignoring year as well. You can use the functions diff and minutes to find the time between each datetime.
T = datetime([2019 11 29 09 00 00; 2020 11 20 10 10 00; 2121 11 22 08 30 00])
T = 3×1 datetime array
29-Nov-2019 09:00:00 20-Nov-2020 10:10:00 22-Nov-2121 08:30:00
Ttemp = T;
Ttemp.Format = 'MM-dd HH:mm:ss';
Ttemp.Year = 2020
Ttemp = 3×1 datetime array
11-29 09:00:00 11-20 10:10:00 11-22 08:30:00
Tnew = sort(Ttemp)
Tnew = 3×1 datetime array
11-20 10:10:00 11-22 08:30:00 11-29 09:00:00
dmin = minutes(diff(Tnew))
dmin = 2×1
2780 10110
  댓글 수: 2
Dan Houck
Dan Houck 2023년 4월 4일
This is basically what I did. It would definitely be trickier if the dates went over 2/29 in some years. Thanks!
Peter Perkins
Peter Perkins 2023년 4월 5일
Yes. The problem is that your question is ill-posed. In general you can't ignore the year. Especially if there are DST timezones involved. But if the timestamps don't straddle a leap day, and you don't care about DST shifts, Cris has the right way to go.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by