How to compare two dates? How to compare two dates? python python

How to compare two dates?


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 < presentTrue>>> datetime(3000, 1, 1) < presentFalse>>> present - datetime(2000, 4, 4)datetime.timedelta(4242, 75703, 762105)


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") and newdate2 = time.strptime(date2, "%d/%m/%Y") to convert them to python's date format. Then, the comparison is obvious:

newdate1 > newdate2 will return False
newdate1 < newdate2 will return True


datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2) will return True.

datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2) will return datetime.timedelta(-1).

datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2) will return datetime.timedelta(1).

see the docs.