MATLAB Answers

0

Find datetime in a vector

Asked by Tiago Dias on 16 Aug 2019
Latest activity Commented on by Tiago Dias on 16 Aug 2019
Accepted Answer by KSSV
Hello,
I want to find the index of two times that belong on a colum with a bunch of timedates
t1 = datetime('10-09-2018 00:00:00','Format','dd-MM-uuuu HH:mm:ss')
t2 = datetime('28-09-2018 23:59:00','Format','dd-MM-uuuu HH:mm:ss')
idx_t1 = find(t_ref==t1)
idx_t2 = find(t_ref==t2)
idx_t1 should be 1020961 and idx_t2 1048320, but the results are empty
Thanks

  0 Comments

Sign in to comment.

1 Answer

KSSV
Answer by KSSV
on 16 Aug 2019
Edited by KSSV
on 16 Aug 2019
 Accepted Answer

Use ismember
Or
idx = knnsearch(datenum(t_ref),datenum(t1)) ;
t_ref(idx)
t1
Or
dt = abs((datenum(t_ref)-datenum(t1))) ;
[val,idx] = min(dt) ;
t_ref(idx)

  4 Comments

Show 1 older comment
Tiago Dias on 16 Aug 2019
Thanks for the knnsearch, that seems to work and give me the index.
Any idea with the other two functions doesnt work?
Guillaume
on 16 Aug 2019
Any idea with the other two functions doesnt work?
Because, despite your statement, neither t1 nor t2 are present within t_ref. Note that the 'Format' property has no influence on the actual content of the datetime, so if they differ at the millisecond level, == will return false, even though you're not displaying the milliseconds.
If you want to get rid of the milliseconds:
t_ref.Second = floor(t_ref.Second); %or round if you prefer rounding to the nearest second
Tiago Dias on 16 Aug 2019
oh ok, I though he would ignore the miliseconds due to the format I specified.
thanks

Sign in to comment.