DateDiff to only calculate number of work days

This was extremely helpful, thank you

To calculate the number of workdays between two dates using the DateDiff function, you can follow these steps in various programming languages and database systems. I’ll provide examples in both SQL and Python:

SQL (SQL Server):

sqlCopy code

-- Calculate the number of workdays between two dates (inclusive)
DECLARE @StartDate DATE = '2023-09-10';
DECLARE @EndDate DATE = '2023-09-20';

DECLARE @WorkdayCount INT = 0;
DECLARE @CurrentDate DATE = @StartDate;

WHILE @CurrentDate <= @EndDate
BEGIN
    -- Check if the current date is a workday (Monday to Friday)
    IF DATEPART(WEEKDAY, @CurrentDate) BETWEEN 2 AND 6
    BEGIN
        SET @WorkdayCount = @WorkdayCount + 1;
    END

    -- Move to the next day
    SET @CurrentDate = DATEADD(DAY, 1, @CurrentDate);
END

-- The @WorkdayCount variable now contains the number of workdays
SELECT @WorkdayCount;

In this SQL example, we first declare the start and end dates. Then, we use a WHILE loop to iterate through each day between those dates, incrementing @WorkdayCount if the current date is a weekday (Monday to Friday).

Python (using datetime):

pythonCopy code

from datetime import datetime, timedelta

def count_workdays(start_date, end_date):
    workday_count = 0
    current_date = start_date

    while current_date <= end_date:
        # Check if the current date is a workday (Monday to Friday)
        if current_date.weekday() < 5:  # 0 = Monday, 4 = Friday
            workday_count += 1
        current_date += timedelta(days=1)

    return workday_count

# Example usage:
start_date = datetime(2023, 9, 10)
end_date = datetime(2023, 9, 20)
result = count_workdays(start_date, end_date)
print(result)

In this Python example, we define a function count_workdays that calculates the number of workdays between two datetime objects. It uses a while loop and the weekday() method to check if each day is a weekday (Monday to Friday) and increments workday_count accordingly.

You can adapt these examples to your specific programming language or database system as needed. The key idea is to iterate through the days between the start and end dates and count only the weekdays as workdays.