How to calculate number of days between two given dates

To calculate the number of days between two dates, you can use the timedelta class from the datetime module.

Here is an example of how to do this:

from datetime import datetime, timedelta

# Parse the start and end dates
start_date = datetime.strptime("2022-01-01", "%Y-%m-%d")
end_date = datetime.strptime("2022-01-31", "%Y-%m-%d")

# Calculate the number of days between the two dates
num_days = (end_date - start_date).days

print(num_days)  # prints 30

This example calculates the number of days between January 1st and January 31st, 2022.

Watch a course Python - The Practical Guide

If you only want to consider business days (i.e., excluding weekends), you can use the weekday method of the datetime object to check if a day is a weekday, and then add up the number of weekdays between the two dates.

from datetime import datetime, timedelta

# Parse the start and end dates
start_date = datetime.strptime("2022-01-01", "%Y-%m-%d")
end_date = datetime.strptime("2022-01-31", "%Y-%m-%d")

# Initialize a counter
num_weekdays = 0

# Iterate over the days between the two dates
for i in range((end_date - start_date).days + 1):
    current_day = start_date + timedelta(days=i)
    # Increment the counter if the day is a weekday
    if current_day.weekday() < 5:
        num_weekdays += 1

print(num_weekdays)  # prints 22

This example calculates the number of weekdays between January 1st and January 31st, 2022.