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

16 次查看(过去 30 天)
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 个评论
K E
K E 2016-11-8
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.

请先登录,再进行评论。

回答(2 个)

Steven Lord
Steven Lord 2016-11-8
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 2016-11-9
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.

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by