25 XP

47. Days between two dates

Beginner math parsing

Write a function days_between(start, end) that takes two dates written as "YYYY-MM-DD" (year, month and day, as in "2024-03-01") and returns how many days apart they are.

  • The answer is never negative: if end comes before start, count the days from end to start.
  • The same date twice is 0 days apart, and one day to the next is 1.
  • Months have their real lengths, and February has 29 days in a leap year.

Python's datetime module already knows the calendar, so there is no need to work out month lengths yourself.

Example 1

Inputstart = "2024-01-01", end = "2024-03-01"
Output60
Explanation31 days of January and 29 of February.

Example 2

Inputstart = "2023-12-25", end = "2023-12-24"
Output1
ExplanationThe end is a day earlier: still 1 day.

Example 3

Inputstart = "2000-01-01", end = "2000-01-01"
Output0
ExplanationThe same date.

Constraints

  • start and end are real dates from "0001-01-01" to "9999-12-31", written with 4, 2 and 2 digits.

Submit also runs 7 more tests you can't see.

Practises Dates and Times (lesson 25).

Code
def days_between(start, end):
    """Count the days between two dates.

    start: str, a date as "YYYY-MM-DD"
    end: str, a date as "YYYY-MM-DD"
    Returns: int, how many days apart they are (0 or more)
    """
    # Write your code here
    pass