🛠️ToolsShed

Date Difference Calculator

Calculate the exact number of days, weeks, and months between two dates.

Frequently Asked Questions

Code Implementation

from datetime import date

def date_difference(start: date, end: date) -> dict:
    """Calculate the difference between two dates in multiple units."""
    if end < start:
        start, end = end, start

    total_days = (end - start).days
    weeks = total_days // 7
    remaining_days = total_days % 7

    # Calendar months and years
    years = end.year - start.year
    months = end.month - start.month
    days = end.day - start.day
    if days < 0:
        months -= 1
        import calendar
        days += calendar.monthrange(end.year, end.month - 1 or 12)[1]
    if months < 0:
        years -= 1
        months += 12

    return {
        "years": years, "months": months, "days": days,
        "total_days": total_days, "total_weeks": total_days / 7,
        "whole_weeks": weeks, "remaining_days": remaining_days,
    }

# Example
d1, d2 = date(2020, 1, 15), date(2024, 6, 20)
diff = date_difference(d1, d2)
print(f"{diff['years']} years, {diff['months']} months, {diff['days']} days")
print(f"Total: {diff['total_days']} days / {diff['whole_weeks']} full weeks")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.