Given two dates date1
and date2
in the format YYYY-MM-DD
, return the number of days between the two dates.
YYYY-MM-DD
?We’ll assume the input format is always valid and as specified.
We can leverage Python’s datetime
module to handle date manipulations and calculations easily. Here’s the plan:
datetime.strptime
.Here’s a Python function to achieve this:
from datetime import datetime
def days_between_dates(date1: str, date2: str) -> int:
# Define the date format
date_format = "%Y-%m-%d"
# Parse the input dates
d1 = datetime.strptime(date1, date_format)
d2 = datetime.strptime(date2, date_format)
# Calculate the difference in days
delta = abs((d2 - d1).days)
return delta
# Example usage:
date1 = "2020-01-15"
date2 = "2019-12-31"
print(days_between_dates(date1, date2)) # Output: 15
The time complexity of this solution is (O(1)) since parsing the dates and computing the difference is done in constant time with respect to the input size.
datetime.strptime
method parses the input string into a datetime
object, making it easier to handle date arithmetic.datetime
objects returns a timedelta
object, from which we can extract the number of days.abs
ensures that we always return a positive number of days regardless of the order of the input dates.This solution should cover typical use cases efficiently and correctly. If additional constraints or edge cases need to be considered, further clarifications can be added.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?