Using Python To Count The Number Of Business Days In A Month?
Solution 1:
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 = 0for i inrange(1, 32):
try:
thisdate = datetime.date(now.year, now.month, i)
except(ValueError):
breakif thisdate.weekday() < 5and thisdate notin holidays: # Monday == 0, Sunday == 6
businessdays += 1print businessdays
Solution 2:
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 inenumerate(week):
# not this month's day or a weekendif day == 0or i >= 5:
continue# or some other control if desired...
weekday_count += 1print weekday_count
that's it.
Solution 3:
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 pythonimport 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] !=0and x[1] < 5])
print"Total working days this month: " + str(working_days)
Solution 4:
I stole this from Sharuzzaman's solution and added a dict for holidays and turned it into a function:
import calendar
cal = calendar.Calendar()
defget_wdim(year,month):
working_days = len([x for x in cal.itermonthdays2(year, month) if x[0] !=0and x[1] < 5])
holidays = {
1:1,
2:1,
4:1,
5:1,
7:1,
9:1,
10:1,
11:4,
12:1
}
returnint(working_days) - holidays.get(month,0)
wdim2022 = [get_wdim(2022,x) for x inlist(range(1,13)) ]
Solution 5:
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.
Post a Comment for "Using Python To Count The Number Of Business Days In A Month?"