Weekdays Between Two Dates

July 5, 2013

Many programming languages provide a library function that calculates a serial number for each day, making it easy to calculate the number of days between two dates; we provide such a function in the Standard Prelude. Sometimes, though, the need is to calculate weekdays rather than total days.

Your task is to write a program that calculates the number of weekdays between two dates. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.


Pages: 1 2

One Response to “Weekdays Between Two Dates”

  1. I found it most intuitive to break the count into whole weeks, days in first week, days in last week

    def get_weekdays_between_helper(d1,d2):
        diff = (d2 - d1).days
        dow1 = d1.isoweekday()
        dow2 = d2.isoweekday()
        dd1 = min (6, dow1)
        dd2 = min (6, dow2)
        # special case - in same week
        if diff < 7 and dow1 <= dow2:
            return (0,dd2 - dd1)
        whole_weeks = diff / 7
        if dow1 <= dow2:
            whole_weeks -= 1
        comps = (
            5 * whole_weeks,
            + dd2-1)
        return sum(comps)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: