How to compare two dates?

Steven Matthews picture Steven Matthews · Nov 15, 2011 · Viewed 517.4k times · Source

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.

Answer

Fred Foo picture Fred Foo · Nov 15, 2011

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)