47. Days between two dates
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
endcomes beforestart, count the days fromendtostart. - 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
start = "2024-01-01", end = "2024-03-01"60Example 2
start = "2023-12-25", end = "2023-12-24"1Example 3
start = "2000-01-01", end = "2000-01-01"0Constraints
startandendare 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).
from datetime import date, thendate.fromisoformat("2024-03-01")turns the text into a date.- Subtracting one date from another gives a
timedelta, a length of time; its.daysis the number of days. .daysis negative when the later date comes first:abs()makes it positive. Counting 30-day months or 365-day years would go wrong around February.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.