Vermillion
Vermillion

Reputation: 1308

Checking for equality of multiple fields of two datetime objects

I want to make sure two datetime objects have the same date and time up to the seconds.

from datetime import datetime

time_a = datetime(2020, 4, 29, 3, 14, 15, 9)
time_b = datetime(2020, 4, 29, 3, 14, 15, 10)

I can't just do assert time_a == time_b, since they have different microseconds.

I could do this with multiple assert statements:

assert time_a.year == time_b.year
assert time_a.month == time_b.month
assert time_a.day == time_b.day
assert time_a.hour == time_b.hour
assert time_a.minute == time_b.minute
assert time_a.second == time_b.second

But this is a bit repetitive. Is there a more concise way to do this?

Upvotes: 0

Views: 207

Answers (3)

GoodDeeds
GoodDeeds

Reputation: 8527

You can check that the difference in time is less than one second using timedelta.

That is,

abs(time_a-time_b) < timedelta(seconds=1)

This is true whenever the absolute value of the difference is less than one second, so it effectively checks for equality up to the seconds. This has the advantage of keeping the original microsecond level information intact in the datetime objects.

Upvotes: 1

arunvelsriram
arunvelsriram

Reputation: 1096

As mentioned in my comment:

from datetime import datetime

time_a = datetime(2020, 4, 29, 3, 14, 15, 9).replace(microsecond=0)
time_b = datetime(2020, 4, 29, 3, 14, 15, 10).replace(microsecond=0)

assert time_a == time_b

Upvotes: 1

Renaud
Renaud

Reputation: 2819

Is removing microseconds will solve your problem:

time_a.replace(microsecond=0) == time_b.replace(microsecond=0)

Upvotes: 0

Related Questions