To solve the problem of calculating the number of days between two dates in Python, we can leverage the built-in datetime module, which simplifies date parsing and arithmetic. Here's a step-by-step implementation:
Approach
- Import the necessary module: Use
datetimefrom thedatetimepackage to handle date objects. - Parse input dates: Convert date strings into
dateobjects (ignoring time components for accuracy). - Calculate the difference: Compute the absolute difference between the two
dateobjects to get atimedeltaobject. - Return days: Extract the number of days from the
timedeltaobject.
Solution Code
from datetime import datetime
def days_between_dates(date1: str, date2: str, date_format: str = '%Y-%m-%d') -> int:
"""
Calculate the absolute number of days between two dates.
Args:
date1: First date string (e.g., '2023-10-01').
date2: Second date string (e.g., '2023-10-05').
date_format: Format of input dates (default: '%Y-%m-%d' for format).
Returns:
Integer number of days between the two dates.
Raises:
ValueError: If dates are not in the specified format.
"""
try:
# Convert strings to date objects (ignores time)
d1 = datetime.strptime(date1, date_format).date()
d2 = datetime.strptime(date2, date_format).date()
# Compute absolute difference in days
return abs((d2 - d1).days)
except ValueError as e:
raise ValueError(f"Invalid date format. Expected format: {date_format}") from e
Explanation
- Flexibility: The function accepts a
date_formatparameter to handle different date string formats (e.g.,'%d/%m/%Y'forDD/MM/YYYY). - Accuracy: Using
date()removes time components, ensuring correct day counts (e.g., no issues with midnight vs non-midnight times). - Error Handling: Catches invalid date formats and provides clear feedback.
Example Usage
# Test with format dates
print(days_between_dates('2020-01-01', '2020-01-05')) # Output: 4
# Test with custom format (DD/MM/YYYY)
print(days_between_dates('28/02/2020', '01/03/2020', '%d/%m/%Y')) # Output: 2 (leap year)
# Test with non-leap year
print(days_between_dates('28/02/2023', '01/03/2023', '%d/%m/%Y')) # Output:1
This solution is efficient, uses standard library tools, and handles edge cases like leap years correctly.
Answer:
The function days_between_dates as provided above solves the problem. It takes two date strings and returns the number of days between them, with support for custom date formats. The code is as follows:
from datetime import datetime
def days_between_dates(date1: str, date2: str, date_format: str = '%Y-%m-%d') -> int:
try:
d1 = datetime.strptime(date1, date_format).date()
d2 = datetime.strptime(date2, date_format).date()
return abs((d2 - d1).days)
except ValueError as e:
raise ValueError(f"Invalid date format. Expected format: {date_format}") from e


作者声明:本文包含人工智能生成内容。