I need to group certain hours of a day into day and night categories from my xlsx file in the format "yyyy-MM-dd'T'HH:mm:ss."
조회 수: 2(최근 30일)
Still familiarizing mysef with MatLab... Essentially I am trying to distriubute my data into day and night to better understand what vessel types are present. The data looks like this, with the heading being bolded
BaseDateTime LAT LON SOG COG Heading VesselName IMO CallSign VesselType
2018-05-18T00:00:07 27.79192 -88.7611 13 148.2 144 SBI MAIA IMO9705304 V7MI4 70
ranging from 2018-05-18 to 2020-06-24. It is a very large exel flie so I an unable to attach it here.
so far I have:
% hold on
shipdata = readtable ('allship2018-2020_1_data.xlsx');
t= datetime(shipdata.BaseDateTime, 'InputFormat',"uuuu-MM-dd'T'HH:mm:ss");
day = timerange('06:00:00','18:00:00');
night = timerange('18:00:01','05:59:59');
for i = 1:length(t)
y(i,:) = isbetween(t,day,night);
yy = unique(y,'rows');
I was thinking about using "isbetween" to find my hours for day (06:00:00 to 18:00:00) and for night (18:00:01 to 05:59:59). I am not sure how to go about this... I tried this code I provide above and got the error "All inputs must be datetime arrays or date/time character vectors or date/time strings"
From there I will graph the data to compare.
Thanks for any help or advice.
Star Strider 2022년 11월 22일
The isbetween functin is the correct approach here, although if you have one set of 12-hour segments and you want to go over several days, a simple logical comparison is all you need.
t = datetime('now') + hours(0:2:64).';
daytime = hour(t)>=6 & hour(t)<18;
plot(t(daytime), ones(size(t(daytime))), '.', 'DisplayName','Daytime')
plot(t(~daytime), -ones(size(t(~daytime))), '.', 'DisplayName','Nighttime')
Experiment to get different results.
Steven Lord 2022년 11월 22일
Let's look at a sample datetime.
t = datetime('now')
What time of day does that represent?
tod = timeofday(t)
Is that time of day during the day? You can either explicitly create a duration by calling duration or just indicate the number of hours after midnight.
dawn = duration(6, 0, 0)
dusk = hours(18)
isDuringTheDay = isbetween(tod, dawn, dusk)
How about 12 hours from now?
then = t+hours(12)
todThen = timeofday(then)
isDuringTheDay12 = isbetween(todThen, dawn, dusk)
Of course, if it's not during the day then it's during the night. It's easier to ask the question "is it daytime" because asking "is it nighttime" would require asking "is it between midnight and dawn" and "is it between dusk and midnight" separately.
A timerange object is used for indexing into a timetable.
Stephen23 2022년 11월 24일
편집: Stephen23 2022년 11월 24일
fnm = 'allship2018-2020_1_data_2.xlsx';
obj = detectImportOptions(fnm);
obj = setvartype(obj,'BaseDateTime','datetime');
tbl = readtable(fnm,obj)
tod = timeofday(tbl.BaseDateTime);
isd = isbetween(tod, duration(6,0,0), duration(18,0,0)); % logical index = is daytime
tbl_day = tbl(isd,:)
tbl_night = tbl(~isd,:)