Similar Problems
Similar Problems not available
Number Of Days Between Two Dates - Leetcode Solution
LeetCode: Number Of Days Between Two Dates Leetcode Solution
Difficulty: Easy
The problem "Number of Days Between Two Dates" on LeetCode asks us to find the number of days between two given dates.
To solve this problem, we need to follow these steps:
- Parse the input dates and convert them to a datetime object.
- Find the difference between the two dates in terms of days using the timedelta function.
- Return the absolute value of the difference, since we want the number of days between the two dates.
Let's start by parsing the input dates and converting them to a datetime object. For this, we will use the datetime library in Python.
import datetime
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
# Parse the input dates and convert them to datetime objects
date1_obj = datetime.datetime.strptime(date1, '%Y-%m-%d')
date2_obj = datetime.datetime.strptime(date2, '%Y-%m-%d')
The strptime()
method of the datetime library converts a string to a datetime object. It takes two arguments: the input string and the format string.
Next, we will find the difference between the two dates in terms of days using the timedelta function.
import datetime
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
# Parse the input dates and convert them to datetime objects
date1_obj = datetime.datetime.strptime(date1, '%Y-%m-%d')
date2_obj = datetime.datetime.strptime(date2, '%Y-%m-%d')
# Find the difference between the two dates in terms of days
delta = date2_obj - date1_obj
return abs(delta.days)
The timedelta()
function returns the difference between two dates as a timedelta object. We use the days
attribute of the timedelta object to get the difference in terms of days.
Finally, we return the absolute value of the difference, since we want the number of days between the two dates.
Here's the complete solution:
import datetime
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
# Parse the input dates and convert them to datetime objects
date1_obj = datetime.datetime.strptime(date1, '%Y-%m-%d')
date2_obj = datetime.datetime.strptime(date2, '%Y-%m-%d')
# Find the difference between the two dates in terms of days
delta = date2_obj - date1_obj
return abs(delta.days)
Some test cases that we can use to verify the correctness of our solution are:
assert Solution().daysBetweenDates("2020-01-01", "2020-01-01") == 0
assert Solution().daysBetweenDates("2020-01-01", "2020-01-02") == 1
assert Solution().daysBetweenDates("2020-01-01", "2019-12-31") == 1
assert Solution().daysBetweenDates("2020-10-31", "2021-01-01") == 62
Number Of Days Between Two Dates Solution Code
1