How to compare two dates?
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.
Solution 1:
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)
Solution 2:
Use time
Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"
You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y")
newdate2 = time.strptime(date2, "%d/%m/%Y")
to convert them to python's date format. Then, the comparison is obvious:
-
newdate1 > newdate2
will returnFalse
-
newdate1 < newdate2
will returnTrue