Counting Working Days Between Two Specified Dates

Abstract: Calculate working days between two dates by excluding weekends and holidays using Excel, Python, or command-line tools.

Created: 2026-09-09 by

Calculating the number of working days between two dates requires excluding weekends and optionally removing public holidays. This process varies significantly depending on your environment, whether you are using spreadsheet software like Excel, scripting in Python or PowerShell, or leveraging command-line tools in Linux and macOS. The core logic always involves iterating through a date range, filtering out non-working days, and returning an integer count.

Using Spreadsheet Software

For most business users, the quickest method to calculate working days is within a spreadsheet application such as Microsoft Excel or Google Sheets. These platforms provide built-in functions designed specifically for this purpose, handling leap years and varying holiday calendars automatically. In Excel, the NETWORKDAYS function is the standard tool. Its syntax is straightforward: =NETWORKDAYS(start_date, end_date, [holidays]). You simply input your start and end dates. If you have a list of holidays defined in a specific range, such as H1:H10, you can include that range as the third argument to exclude those specific days from the count. This function assumes Monday through Friday are working days by default. If your organization operates on a different schedule, such as Sunday through Thursday, you would use the NETWORKDAYS.INTL function, which allows you to specify which days of the week are considered weekends. Google Sheets offers similar functionality with the WORKDAY and NETWORKDAYS functions, though their holiday handling can sometimes be less intuitive than Excel's native integration with local calendar services. For simple calculations without holiday exceptions, the formula remains identical across both platforms, providing immediate results without any coding knowledge required.

Programmatic Solutions with Python

Developers often need to embed date calculations into larger applications. Python provides robust libraries for this task, primarily pandas and datetime. While the standard library datetime module can handle basic arithmetic, it does not inherently understand concepts like "working days" or "holidays." Therefore, external libraries are preferred for accuracy. The pandas.tseries.holiday module is particularly powerful because it includes predefined holiday calendars for various countries. To calculate working days between two dates, you can create a date range and filter out weekends. A common approach involves using pandas.date_range to generate all dates between the start and end points, then using boolean indexing to exclude Saturdays and Sundays. Here is a conceptual example of how this logic is implemented:
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar

start = pd.Timestamp('2023-01-01')
end = pd.Timestamp('2023-01-10')

# Generate all dates in the range
all_dates = pd.date_range(start, end)

# Filter out weekends (Saturday=5, Sunday=6)
workdays = all_dates[~all_dates.dayofweek.isin([5, 6])]

# Optionally remove holidays
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start, end)
working_days_count = len(workdays.difference(holidays))
This script generates a range of dates, removes weekends, and then subtracts any observed federal holidays. The final length of the resulting series gives the precise number of working days. This method is highly scalable and integrates well into data processing pipelines.

Command-Line Tools for Linux and macOS

System administrators and power users frequently prefer command-line interfaces for automation tasks. On Linux and macOS, the date command is versatile but lacks a direct "count working days" flag. However, you can achieve this using shell scripting combined with date and awk. One effective method involves generating a sequence of dates and piping them to a filter that checks the day of the week. The seq command can generate a sequence of numbers representing days, which can then be converted to dates using date -d. By checking if the resulting day name is not Saturday or Sunday, you can count the valid entries. For example, a bash one-liner might look like this:
start_epoch=$(date -d "2023-01-01" +%s)
end_epoch=$(date -d "2023-01-10" +%s)
interval=$(( (end_epoch - start_epoch) / 86400 ))

count=0
for ((i=0; i<=interval; i++)); do
    day=$(date -d "@$((start_epoch + i * 86400))" +%u)
    if [[ $day -lt 6 ]]; then
        ((count++))
    fi
done
echo $count
This script calculates the total days between the epochs, iterates through each day, checks the ISO numeric day of the week (%u), and increments a counter if the day is less than 6 (excluding Saturday and Sunday). Note that this basic script does not account for public holidays. Integrating holiday exclusion in pure shell scripts requires parsing a separate text file of holiday dates, adding complexity.

Windows PowerShell Approaches

Windows environments often rely on PowerShell for administrative tasks. PowerShell has access to the .NET framework, which provides the System.DateTime class. While there is no single cmdlet for counting working days, you can write a simple loop or use LINQ queries to iterate through dates. A more elegant solution in PowerShell involves creating a custom function that leverages .NET methods. You can instantiate a DateTime object for the start and end dates, then loop through each day, checking the DayOfWeek property. If the day is not Saturday or Sunday, increment a counter.
function Get-WorkingDays {
    param(
        [DateTime]$StartDate,
        [DateTime]$EndDate
    )
    
    $count = 0
    $currentDate = $StartDate
    
    while ($currentDate -le $EndDate) {
        if ($currentDate.DayOfWeek -ne 'Saturday' -and $currentDate.DayOfWeek -ne 'Sunday') {
            $count++
        }
        $currentDate = $currentDate.AddDays(1)
    }
    
    return $count
}
This function accepts start and end dates as parameters and returns the integer count of working days. It is clean, readable, and easily extensible to include holiday exclusions by checking against a list of excluded dates.

Frequently Asked Questions

How do I handle different weekend patterns, like Saturday-Sunday vs Sunday-Monday?

In Excel, use the NETWORKDAYS.INTL function and specify the weekend pattern code in the arguments. In Python, adjust the dayofweek filter indices to match your specific weekend days before calculating the difference.

Can I automate this calculation for a large dataset of dates?

Yes, using Python's pandas library allows you to apply these calculations across entire columns of data efficiently. You can vectorize the operation to avoid slow loops, making it suitable for thousands of records.

What if I need to exclude specific company holidays that aren't national holidays?

You must pass a list or array of these specific dates to the holiday parameter in Excel's NETWORKDAYS function. In programming languages, you typically merge your custom holiday list with the standard calendar filters before counting.

Is there a way to do this without writing code in Linux?

While complex, you can use a combination of date and grep to filter out weekend days from a generated date list. However, for regular use, installing a small utility or writing a short shell script is more reliable than chaining multiple command-line tools.

Does the calculation include the start and end dates?

Most standard functions, including Excel's NETWORKDAYS, include both the start and end dates if they fall on a working day. Always verify this behavior in your specific tool, as some custom scripts might exclude one boundary depending on implementation.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More