How to Calculate the Number of Weekdays Between Two Dates in Python

How to Calculate the Number of Weekdays Between Two Dates in Python

Calculating the number of weekdays between two dates is a common operation in many professional and organizational contexts. Typically, weekdays are considered to be Monday through Friday, excluding weekends (Saturday and Sunday). 

Whether scheduling events, calculating delivery times, or managing workflows, the ability to compute weekdays accurately is essential. Python’s datetime, numpy, and dateutil modules offer several tools that streamline these date-related operations, enhancing both efficiency and precision in handling such tasks.

Let’s explore several methods to calculate the number of weekdays between two dates in Python:

1. Using a Simple Loop

The most straightforward method is to iterate through each day between the start and end dates, counting only the weekdays:

from datetime import datetime, timedelta

def count_weekdays(start_date, end_date):
    current_date = start_date
    weekdays = 0
    while current_date <= end_date:
        if current_date.weekday() < 5:  # Monday = 0, Friday = 4
            weekdays += 1
        current_date += timedelta(days=1)
    return weekdays

# Example usage
start = datetime(2024, 8, 1)
end = datetime(2024, 8, 31)
weekdays = count_weekdays(start, end)
print(f"Number of weekdays between {start.date()} and {end.date()}: {weekdays}")

Expected output:

Number of weekdays between 2024-08-01 and 2024-08-31: 22

This method is simple to understand but can be inefficient for large date ranges.

2. Using NumPy for Faster Calculation

For larger date ranges, we can use NumPy to speed up the calculation:

import numpy as np
from datetime import datetime, timedelta

def count_weekdays_numpy(start_date, end_date):
    days = np.busday_count(start_date.date(), end_date.date() + timedelta(days=1))
    return int(days)

# Example usage
start = datetime(2024, 8, 1)
end = datetime(2024, 11, 30)
weekdays = count_weekdays_numpy(start, end)
print(f"Number of weekdays between {start.date()} and {end.date()}: {weekdays}")

Expected output:

Number of weekdays between 2024-08-01 and 2024-11-30: 87

The np.busday_count function offers several advantages:

  • Efficiency: Implemented in C, making it faster than Python loops, especially for large date ranges.
  • Flexibility: Allows customization of business days and holidays.
  • Vectorization: Can handle arrays of date ranges for batch processing.

Note: We add one day to the end date because np.busday_count uses a half-open interval [start, end), including the start date but excluding the end date.

While this method requires the NumPy library, its speed and flexibility make it an excellent choice for data science and financial applications where performance needs to be optimized. 

3. Accounting for Holidays

In many real-world scenarios, you might need to exclude holidays from your weekday count. Here’s how you can modify the function to account for holidays:

from datetime import datetime, timedelta

def count_weekdays_excluding_holidays(start_date, end_date, holidays):
    current_date = start_date
    weekdays = 0
    while current_date <= end_date:
        if current_date.weekday() < 5 and current_date.date() not in holidays:
            weekdays += 1
        current_date += timedelta(days=1)
    return weekdays

# Example usage
start = datetime(2024, 8, 1)
end = datetime(2024, 8, 31)
holidays = [datetime(2024, 8, 15).date()]  # Example holiday
weekdays = count_weekdays_excluding_holidays(start, end, holidays)
print(f"Number of weekdays (excluding holidays) between {start.date()} and {end.date()}: {weekdays}")

Expected output:

Number of weekdays (excluding holidays) between 2024-08-01 and 2024-08-31: 21

This function allows you to pass a list of holiday dates to be excluded from the weekday count.

4. Using dateutil for More Flexibility

The dateutil library provides more advanced date handling capabilities:

from dateutil import rrule
from datetime import datetime

def count_weekdays_dateutil(start_date, end_date):
    weekdays = rrule.rrule(rrule.DAILY, dtstart=start_date, until=end_date, byweekday=(rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR))
    return len(list(weekdays))

# Example usage
start = datetime(2024, 8, 1)
end = datetime(2024, 8, 31)
weekdays = count_weekdays_dateutil(start, end)
print(f"Number of weekdays between {start.date()} and {end.date()}: {weekdays}")

Expected output:

Number of weekdays between 2024-08-01 and 2024-08-31: 22

The dateutil library offers more flexibility in several ways:

  • Complex recurrence rules: It allows you to define sophisticated patterns for recurring events, which is particularly useful for business logic involving schedules or periodic events.
  • Custom weekday definitions: You can easily modify what constitutes a “weekday” by adjusting the byweekday parameter. For instance, you could include Saturday as a workday for certain business contexts.
  • Time zone handling: dateutil provides robust support for working with different time zones, which is useful for applications dealing with global schedules or events.
  • Date parsing: The library offers powerful date parsing capabilities, allowing you to work with dates in various string formats.

While the dateutil approach might be slightly more complex for simple cases, its flexibility makes it a powerful tool for handling a wide range of date-related calculations in more sophisticated applications.

Conclusion

Calculating the number of weekdays between two dates in Python can be accomplished using various methods, each with its own advantages. The simple loop method is easy to understand and modify, while NumPy provides faster calculations for large date ranges. Accounting for holidays adds an important layer of accuracy for many real-world applications, and using dateutil offers more flexibility for complex date handling.

When working with dates, it’s important to consider factors such as time zones and the specific definition of a “business day” in your context. These examples provide a solid foundation for date-related calculations in your Python projects, enhancing your ability to handle time-based data effectively in different scenarios. 

Leave a Reply

Your email address will not be published. Required fields are marked *