How to get the index from a datetime array corresponding to a time duration?

19 views (last 30 days)
Hi I am trying to get the starting and ending index from a datetime array that corresponds to a specific time duration.
Find below my code for a general datetime array
t1 = datetime('23-Feb-2015 09:43:08')
num=2000
t2 = t1 + seconds(1:num)
I am interested in getting the starting and ending index from t2 with a time step durations of 5min.
index1=starting and ending index from t2 which corresponding to first 5 min.
index2=starting and ending index from t2 which corresponding to next 5 min .
.
.
.
index= starting and ending index from t2 which corresponds to remaining time.
I tried something using "minutes" but i do not know how to access the starting and ending index from t2. Can you please help?
  1 Comment
K E
K E on 8 Nov 2016
I am also having trouble trying to get the index to datetime objects that are later than a certain time. I wish Matlab would expand its examples on using datetime to include this, and other kinds of 'time math' operations.

Sign in to comment.

Answers (2)

Steven Lord
Steven Lord on 8 Nov 2016
start = datetime('now');
vec = start + hours(0:24).'; % datetime + duration = datetime
midnight = dateshift(start, 'end', 'day');
pastMidnight = vec > midnight; % relational operators work
T = table(vec, pastMidnight)
The first element of the pastMidnight variable inside the table T (or the logical vector pastMidnight) that is true should be the first time in the vec variable inside the table T (or the datetime array vec) that is past midnight. I didn't need to display the information as a table, but I feel it formats the data nicely.
Logical indexing also works.
vec(pastMidnight)
If you are storing your data in a timetable, the retime method and indexing using withtol or timerange objects may be of interest or use to you.

Peter Perkins
Peter Perkins on 9 Nov 2016
There are many ways to do this, I bet. Here's one:
>> bin = floor((t2 - t1) ./ minutes(5)) + 1;
>> i2 = [find(diff(bin)>0) length(bin)+1];
>> i1 = [1 i2(1:end-1)+1];
>> [i1; i2]
ans =
1 300 600 900 1200 1500 1800
299 599 899 1199 1499 1799 2001
In general, with arbitrary time points or bin size, you'd proably want to substitute discretize for floor(...) to avoid any round-off issues, but with whole seconds and whole minutes there is no issue.

Categories

Find more on Dates and Time in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!