Skip to content

Instantly share code, notes, and snippets.

@chmouel
Created October 10, 2024 17:09
Show Gist options
  • Save chmouel/1943835059ce2bb5e8cd8ca6418d0af1 to your computer and use it in GitHub Desktop.
Save chmouel/1943835059ce2bb5e8cd8ca6418d0af1 to your computer and use it in GitHub Desktop.
from datetime import datetime, timedelta
def calculate_start_date_and_months(end_date_str, num_weeks):
# Convert end_date_str to a datetime object
end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
# Calculate the number of days to subtract
num_days = num_weeks * 7
# Calculate the start date
start_date = end_date - timedelta(days=num_days)
# Calculate the number of months between start_date and end_date
num_months = (
(end_date.year - start_date.year) * 12 + end_date.month - start_date.month
)
# Return the start date and number of months in the desired format
return start_date.strftime("%Y-%m-%d"), num_months
# Example usage
end_date = "2025-06-29"
num_weeks = 26
start_date, num_months = calculate_start_date_and_months(end_date, num_weeks)
print(f"Start date: {start_date}, Number of months: {num_months}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment