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
You could take a look at datetime.datetime.dayofweek()
but if you are not allowed to use an external library then you need to:
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
This is relatively simple, just break it down into steps:
Combine these steps and you'll have a working method.
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.
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)
UPDATE: OP can't use any external libraries. Then you will have to build some tables based on determining the day of the week from the calendar.
The formula is d + m + y + y/4 + (c mod 7), where: d is the day of the month, m is the month's number in the months table, y is the last two digits of the year, and c is the century number.
It's tedious but not impossible!
ORIG answer: It's quite tedious to code yourself, because August 01, 2013 and August 01, 2012 are not necessarily the same day of the week. I'd start with the 'date' class in python (details here
from datetime import date
datetime.date(2002, 3, 11)
t = d.timetuple()
for i in t:
print i
In particular, check out the 'datetime.weekday()' function.