How to extract hour+minute from DateTime vector ?

조회 수: 34 (최근 30일)
Doug Leaffer
Doug Leaffer 2022년 6월 8일
댓글: Peter Perkins 2022년 6월 13일
Q: how do I best extract BOTH the hour + minute from a DateTime vector in MATLAB ? My DateTime format is: 15-Apr-2016 11:43:11
I need to fine-tune the rush hours to the exact time ranges below. My current code, below, works but does not include the 'minutes'. Please help.
t = datetime(data.DateTime);d = day(t,'dayofyear'); DayofYr = d;
tf = isweekend(t); % returns logical 1 = true = weekend, else 0
Wkend = tf;
h = hour(data.DateTime); % extract hour from Datetime vector
isAMRush = h>=7 & h<9 ==1; % needs to be revised to: 745a -845a morning rush
isPMRush = h>=15 & h<17 ==1; % needs to be revised to: 330p -430p afternoon rush
%
  댓글 수: 2
Stephen23
Stephen23 2022년 6월 8일
D = datetime(2016,4,5,[8;11],43,11)
D = 2×1 datetime array
05-Apr-2016 08:43:11 05-Apr-2016 11:43:11
isAMRush = isbetween(timeofday(D),duration(7,45,0),duration(8,45,0))
isAMRush = 2×1 logical array
1 0
Doug Leaffer
Doug Leaffer 2022년 6월 8일
Iwill run this code suggestion. Thank you for the advice and the example output, which is helpful

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

채택된 답변

Stephen23
Stephen23 2022년 6월 8일
D = datetime(2016,4,5,[8;11],43,11)
D = 2×1 datetime array
05-Apr-2016 08:43:11 05-Apr-2016 11:43:11
isAMRush = isbetween(timeofday(D),duration(7,45,0),duration(8,45,0))
isAMRush = 2×1 logical array
1 0
  댓글 수: 1
Peter Perkins
Peter Perkins 2022년 6월 13일
Right.
I mean the real answer is, "you hardly ever need to actually explicitly extract individual time components."

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

추가 답변 (2개)

dpb
dpb 2022년 6월 8일
Convert to durations and use
isAMRush=iswithin(duration(hour(t),minute(t),0),duration(7,45,0),duration(8,45,0));

Steven Lord
Steven Lord 2022년 6월 8일
d = datetime('15-Apr-2016 11:43:11')
d = datetime
15-Apr-2016 11:43:11
[h, m, s] = hms(d)
h = 11
m = 43
s = 11
or
tod = timeofday(d)
tod = duration
11:43:11

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by