freezegun icon indicating copy to clipboard operation
freezegun copied to clipboard

can't compare datetime.datetime to datetime.date

Open applecat opened this issue 4 years ago • 3 comments

I have this line in my code: if self.begin and datetime.now() < self.begin:

And some tests for that code:

@pytest.mark.parametrize("freeze_time, begin", [
    (datetime(2020, 3, 1), datetime(2020, 3, 3)),
    (datetime(2020, 3, 2, 23, 50), datetime(2020, 3, 3)),
])
def test_code(freezer, freeze_time, begin):
    freezer.move_to(freeze_time)
    ...

Tests passed, every thing is ok, but in production I've got this error: Exception Value: can't compare datetime.datetime to datetime.date

I figured out that self.begin was a datetime.date object, so python can't compare it to datetime.datetime.

But in my tests I see comparison between FakeDatetime and FakeDate and everything goes well:

<class 'freezegun.api.FakeDatetime'> 2020-03-02 23:50:00
<class 'freezegun.api.FakeDate'> 2020-03-03

Is it expected behavior? Can I catch this type of errors with freezegun?

applecat avatar Mar 16 '20 19:03 applecat

This is absolutely a bug.

boxed avatar Mar 17 '20 08:03 boxed

@applecat I want to fix this bug, but I can't reproduce this behavior. Comparison between FakeDatetime and FakeDate raises an error TypeError: can't compare FakeDatetime to FakeDate in my case. In your tests you are setting parameter begin to datetime(2020, 3, 3) not date(2020, 3, 3) so I guess that's why the tests pass. Will this fix your problem?

mkarys avatar Jun 17 '20 10:06 mkarys

@applecat I want to fix this bug, but I can't reproduce this behavior. Comparison between FakeDatetime and FakeDate raises an error TypeError: can't compare FakeDatetime to FakeDate in my case. In your tests you are setting parameter begin to datetime(2020, 3, 3) not date(2020, 3, 3) so I guess that's why the tests pass. Will this fix your problem?

Looks like the problem happens when comparing FakeDate and standard datetime objects

In [1]: from freezegun.api import FakeDate
In [2]: import datetime
In [3]: d = FakeDate(2021, 3, 7)
In [4]: n = datetime.datetime(2021, 2, 21, 13, 0)
In [5]: d > n
Out[5]: True
In [6]: n > d
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-61f7fae57601> in <module>
----> 1 n > d

TypeError: can't compare datetime.datetime to FakeDate
In [7]: d == n
Out[7]: False

All comparisons should give TypeError

akuzminov avatar May 24 '21 05:05 akuzminov