MATLAB Answers

Subset timetable based on datetime values

8 views (last 30 days)
Louise Wilson
Louise Wilson on 17 Mar 2020
Edited: Adam Danz on 23 Mar 2020
Hello, I have a timetable which has datetime values incrementing in ten minute intervals over a year, e.g.:
DateTime BoatCount PV
___________________ _________ __
29.05.2019 10:30:00 1 0
29.05.2019 10:40:00 0 0
29.05.2019 10:50:00 0 0
29.05.2019 11:00:00 0 0
29.05.2019 11:10:00 0 0
29.05.2019 11:20:00 0 0
29.05.2019 11:30:00 0 0
29.05.2019 11:40:00 0 0
I want to subset this data so I am only including values recorded in daylight hours e.g. 0600-2030. How do I subset the data by datetime values? Something like...
daylighthours=TT2(TT2.DateTime=='29/05/2019 06:00:00' : '29/05/2019 20:30:00')
but which would cycle through each day of the year


Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 17 Mar 2020
Here's a demo that determines which rows of a timetable have times that are between two values.
% Create a demo timetable
TT = timetable((datetime('now') - minutes(0:248:60000))', rand(242,1));
% Get time-part (in duration format)
dur = TT.Time - dateshift(TT.Time, 'start', 'day');
% Define sunrise and sunset
sunrise = duration(6,30,0); % 6:00
sunset = duration(20,30,0); % 20:30
% Determine which times are between sunrise and sunset
idx = dur >= sunrise & dur <= sunset;
% Isolate rows of timetable that are during daylight
Note: Sunrise and sunset are not fixed every day. A better approach would be to us a vector of sunrise and sunset times the same length as the datetime column and to determine whether each row is between those associated sunrise/sunset values.


Akira Agata
Akira Agata on 18 Mar 2020
To get time-part in duration format, you can also do that using timeofday function, like:
% Get time-part (in duration format)
dur = timeofday(TT.time);
Louise Wilson
Louise Wilson on 18 Mar 2020
Hi Adam, that is a really useful point! Thank you. Should I do this vector manually or do you think there is a faster way to get these times?
Adam Danz
Adam Danz on 18 Mar 2020
Thanks, @Akira Agata
@Louise Wilson , sunrise and sunset times not only depend on time-of-year but also on location. You could either search for and download those values or you may be able to compute them.
Update, here's an algorithm to follow
Update 2, Loren has just posted a blog where this algorithm is demonstrated within a GIF image.

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!