Delete rows from a table using a condition on datetimes

2 views (last 30 days)
Hello!
I'm working with a table T having two separate datetime columns containing dates ('M\d\yyyy'): let' say the first column is called dates1 and the second is called dates2. I want to find a way to keep ONLY the rows where the column dates2 is one day ahead of column dates1.
Can something like this work? I'm dealing with a huge set of data and I don't want to make mistakes
indexes=(T.dates1+1)~=T.dates2; %Positions to delete
T(indexes,:)=[]; %delete all the columns in those positions
Hope that the question is clear.
Thank you!

Accepted Answer

Steven Lord
Steven Lord on 27 Jan 2022
For the sake of humans reading your code I'd be more explicit and give that 1 some units.
rng default
t = datetime('today')
t = datetime
27-Jan-2022
v1 = t + caldays(randi([-7 7], 1, 5))
v1 = 1×5 datetime array
01-Feb-2022 02-Feb-2022 21-Jan-2022 02-Feb-2022 29-Jan-2022
v2 = v1 + caldays(randi([-1 1], 1, 5))
v2 = 1×5 datetime array
31-Jan-2022 01-Feb-2022 21-Jan-2022 03-Feb-2022 30-Jan-2022
The fourth and fifth elements of v2 are 1 day after the corresponding elements of v1.
isOneDayLater = v2 == (v1 + caldays(1))
isOneDayLater = 1×5 logical array
0 0 0 1 1
Why do I use caldays instead of just days?
daylightSavingsTimeStarts = datetime(2022, 3, 13, 'TimeZone', 'America/New_York')
daylightSavingsTimeStarts = datetime
13-Mar-2022
daylightSavingsTimeStarts + days(1) % a 23 hour long day
ans = datetime
14-Mar-2022 01:00:00
daylightSavingsTimeStarts + caldays(1)
ans = datetime
14-Mar-2022
days(1) represents 24 hours. caldays(1) represents one calendar day, no matter how many hours that calendar day contains. That could be 23 hours, 24 hours, or 25 hours.
datetime(2022, 11, 6, 'TimeZone', 'America/New_York') + days(1) % DST ends
ans = datetime
06-Nov-2022 23:00:00

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!