Number of Days Between Two Dates

To count the number of days between two dates, we can utilize the built-in datetime module in Python. Here’s a simple way to do it:

1
2
3
4
5
6
7
from datetime import datetime

class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        d1 = datetime.strptime(date1, "%Y-%m-%d")
        d2 = datetime.strptime(date2, "%Y-%m-%d")
        return abs((d2 - d1).days)

In the code above:

  1. The datetime.strptime() function is used to convert the date strings into datetime objects. The format “%Y-%m-%d” is passed to indicate the format of the date string.

  2. Then we subtract one datetime object from the other, which results in a timedelta object representing the difference between the two dates.

  3. Finally, the .days attribute of the timedelta object is accessed to get the number of days between the two dates.

  4. We wrap this in an abs() function to ensure the result is always positive, regardless of the order of dates.

This works because Python’s datetime module can handle the complexity of the calendar, including leap years, automatically.