Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to count the number of business days in a month?

Tags:

python

date

I am trying to write a Python script that will calculate how many business days are in the current month. For instance if month = August then businessDays = 22.

Here is my code for discovering the month:

def numToMonth( num ):
   months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
   return str(months[ num - 1 ])

This code works fine, and I could hard code another function to match the month with how many days that month should contain...but this does not help me with business days.

Any help? I'm used to C, C++ so please don't bash my Python "skills".

Edit: I cannot install any extra libraries or modules on my machine, so please post answers using default Python modules. (Python 2.7, datetime etc.) Also, my PC has Windows 7 OS.

like image 344
Jacob Bridges Avatar asked Aug 14 '13 13:08

Jacob Bridges


3 Answers

This is a long-winded way, but at least it works and doesn't require anything other than the standard modules.

import datetime

now = datetime.datetime.now()
holidays = {datetime.date(now.year, 8, 14)} # you can add more here
businessdays = 0
for i in range(1, 32):
    try:
        thisdate = datetime.date(now.year, now.month, i)
    except(ValueError):
        break
    if thisdate.weekday() < 5 and thisdate not in holidays: # Monday == 0, Sunday == 6 
        businessdays += 1

print businessdays
like image 154
chthonicdaemon Avatar answered Nov 14 '22 11:11

chthonicdaemon


I would simply use built-in module calendar:

import calendar

weekday_count = 0
cal = calendar.Calendar()

for week in cal.monthdayscalendar(2013, 8):
    for i, day in enumerate(week):
        # not this month's day or a weekend
        if day == 0 or i >= 5:
            continue
        # or some other control if desired...
        weekday_count += 1

print weekday_count

that's it.

like image 9
kirpit Avatar answered Nov 14 '22 12:11

kirpit


I would like to add my answer.

I'm using Calendar, list comprehension, and length to count how many days is the working day a particular month.

Here is my code:

#!/bin/env python

import calendar
import datetime

now = datetime.datetime.now()

cal = calendar.Calendar()

working_days = len([x for x in cal.itermonthdays2(now.year, now.month) if x[0] !=0 and x[1] < 5])

print "Total working days this month: " + str(working_days)
like image 7
Sharuzzaman Ahmat Raslan Avatar answered Nov 14 '22 11:11

Sharuzzaman Ahmat Raslan