Fix Python – How to compare two dates?

Question

Asked By – Steven Matthews

How would I compare two dates to see which is later, using Python?

For example, I want to check if the current date is past the last date in this list I am creating, of holiday dates, so that it will send an email automatically, telling the admin to update the holiday.txt file.

Now we will see solution for issue: How to compare two dates?


Answer

Use the datetime method and the operator < and its kin.

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)

This question is answered By – Fred Foo

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0