+1 vote
in Programming Languages by (56.8k points)
edited by
I want to compare two dates to know which is the latest date. Which Python module should I use for it? Also, how can I find the difference between those two dates?

E.g.

date1 = "2023-04-21"

date2 = "2024-04-13"

1 Answer

+3 votes
by (351k points)
selected by
 
Best answer

You can use the Python module datetime to compare dates and find the difference between them. The module's strptime() method creates a datetime object from the date given in string format.

Here is an example to show how to use the datetime module:

from datetime import datetime
date1 = "2023-04-21"
date2 = "2024-04-13"
d1 = datetime.strptime(date1, "%Y-%m-%d")
d2 = datetime.strptime(date2, "%Y-%m-%d")
if d2 > d1:
    gap = (d2-d1).days
    print("date2 is latest and difference is {0} days".format(gap))
else:
    gap = (d1-d2).days
    print("date1 is latest and difference is {0} days".format(gap))


...