+4 votes
in Programming Languages by (73.8k points)
edited by
How can I compare a date with two other dates in Python?

E.g.

d1 = '2020-03-01'

d2 = '2020-04-01'

d3 = '2020-05-01'

The condition d1 <= d2 and d2 <= d3 should return True.

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use either datetime or time module to compare two dates. Both modules have function strptime() to convert a string to datetime.

Using datetime:

>>> from datetime import datetime
>>> d1 = '2020-03-01'
>>> d2 = '2020-04-01'
>>> d3 = '2020-05-01'
>>> datetime.strptime(d1, "%Y-%m-%d") <= datetime.strptime(d2, "%Y-%m-%d") <= datetime.strptime(d3, "%Y-%m-%d")
True

Using time:

>>> import time
>>> d1 = '2020-03-01'
>>> d2 = '2020-04-01'
>>> d3 = '2020-05-01'
>>> time.strptime(d1, "%Y-%m-%d") <= time.strptime(d2, "%Y-%m-%d") <= time.strptime(d3, "%Y-%m-%d")
True 

by (71.8k points)
Even string comparison should work.
E.g.

>>> d1 = '2020-03-01'
>>> d2 = '2020-04-01'
>>> d3 = '2020-05-01'
>>> d1 <= d2 <= d3
True

...