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

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.

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

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)

I stole this from Sharuzzaman's solution and added a dict for holidays and turned it into a function:
import calendar
cal = calendar.Calendar()
def get_wdim(year,month):
working_days = len([x for x in cal.itermonthdays2(year, month) if x[0] !=0 and x[1] < 5])
holidays = {
1:1,
2:1,
4:1,
5:1,
7:1,
9:1,
10:1,
11:4,
12:1
}
return int(working_days) - holidays.get(month,0)
wdim2022 = [get_wdim(2022,x) for x in list(range(1,13)) ]

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.

This is relatively simple, just break it down into steps:
You need to be able to loop through the days in a month.
You need to be able to determine the day of a week that any given date falls on. Wikipedia lists some methods.
Then you need only flag days of the week as business days or not.
Combine these steps and you'll have a working method.

You could take a look at datetime.datetime.dayofweek() but if you are not allowed to use an external library then you need to:
pick a date that you know the day of week of - best if it is a
Monday
come up with a formulae for the number of days since then that the
first of a given month is.
for each of the days in the month the (number of days since your
day) % 7 in [5, 6] is a weekend.

Acknowledging the OP stated external libraries could not be used, given the ranking of the question in searches (together with the fact this wasnt stated in the title), I figured I'd share a pandas solution which provides a solution spanning multiple months, with results presented in a df.
import pandas as pd
business_days = pd.date_range(start, end, freq='B')
pd.DataFrame(index=business_days, data=[1] * len(business_days)).resample('M').sum()

Related

how to iterate over date using for loop in python

I am creating an app where I have two values, a committee starting date for e-g 2022,01,02 and for how many months it will continue here it is (4months). Now I am saving some data in my database month wise and also these dates will save too. now the issue is I am getting right result if the number of month is less than or equal to 12 using this.
number of memebrs = 12
starting date = 2022,01,01
for i in range(1,17):
print('date', (2022,i,10))
but the issue comes when the months are greater than 12 so than date start printing 2022,01,13 which is false because I also want to increment the year to 2023, I feel like this is not really a good idea very inefficient looking way. can anyone tell me is there any other way to do this.
While you can use the datetime library to handle dates, it doesn't provide any methods to increase dates month by month.
Now, previous suggestions/answers suggest you increase the year when month == 12, but that will cause December to be skipped. Also, your code doesn't consider any given month in the starting date. So a better solution would be:
>>> year = 2022
>>> month = 7
>>> day = 23
>>>
>>> for i in range(1, 8):
... month += 1
... if month == 13:
... month = 1
... year += 1
... print(f'{year}-{month}-{day}')
...
2022-8-23
2022-9-23
2022-10-23
2022-11-23
2022-12-23
2023-1-23
2023-2-23
you could do something like this:
date = [2022,1,10]
for i in range(1,17):
if i%12==0:
date[0]+=1
date[1]=1
print('date', (time[0],i,time[2]))
By the tone of your question i think you are a beginner, so i won't
recommend you to use datetime module and i appreciate that you tried to do it on your own.
What i dont appreciate is that why cant you just use if statements and create variables for year and date
yr = 2022
dt = 1
for i in range(1,17):
print('date', (yr,i,dt))
if i % 12 == 0:
yr += 1
mn = 1
I also want to share the modern aproach using datetime module. But it requires some modules.
In your cmd enter the command
pip install python-dateutil
Once installed close cmd and refresh your ide
this is the code you may want to use
from datetime import datetime
from dateutil.relativedelta import relativedelta
date_time = datetime(2022, 1, 1) #Creating a Date object
for i in range(1, 17):
date = date_time.date()
print(date)
date_time = date_time + relativedelta(months=1)

How to get a list of days using Python's QuantLib

Given a calendar, I wanted to get a list of first 2 business days (week starts from Sunday) of the week prior to 4 weeks to the week of a given date.
Is there any way to get the list of such days? I am using QuantLib module in Python.
Below is my implementation so far -
import QuantLib as ql
import pandas as pd
date = ql.Date(2, 7, 2020)
date_prev = date - ql.Period(4, ql.Weeks)
us_calendar = ql.UnitedStates()
print(date)
print(date_prev)
As you see, above code is just blindly deducting 4 weeks from date, without consideration from us_calendar, nor providing the list of first 2 days on that week which I was looking for
Any pointer will be very helpful.
Something like this:
import QuantLib as ql
calendar = ql.UnitedStates()
start = ql.Date(7,5,2020)
previous = calendar.advance(start, -4, ql.Weeks)
days = [calendar.advance(previous, n, ql.Days) for n in [1,2]]
print(days)
[Date(10,4,2020), Date(13,4,2020)]
I'm more than 2 years late in answering, but just in case it's still useful, I'd do something like this:
date = ql.Date(2, 7, 2020)
# 4 weeks before:
d = date - ql.Period(4, ql.Weeks)
# if needed, go back to the Sunday of that week:
while d.weekday() != ql.Sunday:
d = d - 1
# now get the first two business days:
d1 = us_calendar.advance(d, 1, ql.Days)
d2 = us_calendar.advance(d1, 1, ql.Days)
print([d1, d2])

Python get date from weekday

Let's say I have 11 Sessions for myself to complete. I haven't set dates for these sessions but rather just weekdays where one session would take place. Let's say when scheduling these sessions, I chose MON, TUE and WED. This means that after today, I want the dates to 11 my sessions which would be 4 Mondays, 4 Tuesdays and 3 Wednesdays from now after which my sessions will be completed.
I want to automatically get the dates for these days until there are 11 dates in total.
I really hope this makes sense... Please help me. I've been scratching my head over this for 3 hours straight.
Thanks,
You can use pd.date_range and the CustomBusinessDay object to do this very easily.
You can use the CustomBusinessDay to specify your "business days" and create your date range from it:
import pandas
from datetime import date
session_days = pd.offset.CustomBusinessDay(weekmask="Mon Tue Wed")
dates = pd.date_range(date.today(), freq=session_days, periods=11)
I figured it out a while ago but my internet died. All it took was Dunhill and some rest.
import datetime
def get_dates():
#This is the max number of dates you want. In my case, sessions.
required_sessions = 11
#These are the weekdays you want these sessions to be
days = [1,2,3]
#An empty list to store the dates you get
dates = []
#Initialize a variable for the while loop
current_sessions = 0
#I will start counting from today but you can choose any date
now = datetime.datetime.now()
#For my use case, I don't want a session on the same day I run this function.
#I will start counting from the next day
if now.weekday() in days:
now = now + datetime.timedelta(days=1)
while current_sessions != required_sessions:
#Iterate over every day in your desired days
for day in days:
#Just a precautionary measure so the for loops breaks as soon as you have the max number of dates
#Or the while loop will run for ever
if current_sessions == required_sessions:
break
#If it's Saturday, you wanna hop onto the next week
if now.weekday() == 6:
#Check if Sunday is in the days, add it
if 0 in days:
date = now + datetime.timedelta(days=1)
dates.append(date)
current_sessions += 1
now = date
else:
#Explains itself.
if now.weekday() == day:
dates.append(now)
now = now + datetime.timedelta(days=1)
current_sessions += 1
#If the weekday today is greater than the day you're iterating over, this means you've iterated over all the days in a NUMERIC ORDER
#NOTE: This only works if the days in your "days" list are in a correct numeric order meaning 0 - 6. If it's random, you'll have trouble
elif not now.weekday() > day:
difference = day - now.weekday()
date = now + datetime.timedelta(days=difference)
dates.append(date)
now = date
current_sessions += 1
#Reset the cycle after the for loop is done so you can hop on to the next week.
reset_cycle_days = 6 - now.weekday()
if reset_cycle_days == 0:
original_now = now + datetime.timedelta(days=1)
now = original_now
else:
original_now = now + datetime.timedelta(days=reset_cycle_days)
now = original_now
for date in dates:(
print(date.strftime("%d/%m/%y"), date.weekday()))
Btw, I know this answer is pointless compared to #Daniel Geffen 's answer. If I were you, I would definitely choose his answer as it is very simple. This was just my contribution to my own question in case anyone would want to jump into the "technicalities" of how it's done by just using datetime. For me, this works best as I'm having issues with _bz2 in Python3.7 .
Thank you all for your help.

Get number of days in a specific month that are in a date range

Haven't been able to find an answer to this problem. Basically what I'm trying to do is this:
Take a daterange, for example October 10th to November 25th. What is the best algorithm for determining how many of the days in the daterange are in October and how many are in November.
Something like this:
def daysInMonthFromDaterange(daterange, month):
# do stuff
return days
I know that this is pretty easy to implement, I'm just wondering if there's a very good or efficient algorithm.
Thanks
Borrowing the algorithm from this answer How do I divide a date range into months in Python?
, this might work. The inputs are in date format, but can be changed to date strings if preferred:
import datetime
begin = '2018-10-10'
end = '2018-11-25'
dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
#print(today)
tomorrow = today + one_day
if tomorrow.month != today.month:
start_dates.append(tomorrow)
end_dates.append(today)
today = tomorrow
end_dates.append(dt_end)
out_fmt = '%d %B %Y'
for start, end in zip(start_dates,end_dates):
diff = (end - start).days
print('{} to {}: {} days'.format(start.strftime(out_fmt), end.strftime(out_fmt), diff))
result:
10 October 2018 to 31 October 2018: 21 days
01 November 2018 to 25 November 2018: 24 days
The problem as stated may not have a unique answer. For example what should you get from daysInMonthFromDaterange('Feb 15 - Mar 15', 'February')? That will depend on the year!
But if you substitute actual days, I would suggest converting from dates to integer days, using the first of the month to the first of the next month as your definition of a month. This is now reduced to intersecting intervals of integers, which is much easier.
The assumption that the first of the month always happened deals with months of different lengths, variable length months, and even correctly handles the traditional placement of the switch from the Julian calendar to the Gregorian. See cal 1752 for that. (It will not handle that switch for all locations though. Should you be dealing with a library that does Romanian dates in 1919, you could have a problem...)
You can use the datetime module:
from datetime import datetime
start = datetime(2018,10,10)
end = datetime(2018,11,25)
print((end - start).days)
Something like this would work:
def daysInMonthFromDaterange(date1, date2, month):
return [x for x in range(date1.toordinal(), date2.toordinal()) if datetime.date.fromordinal(x).year == month.year and datetime.date.fromordinal(x).month == month.month]
print(len(days_in_month(date(2018,10,10), date(2018,11,25), date(2018,10,01))))
This just loops through all the days between date1 and date2, and returns it as part of a list if it matches the year and month of the third argument.

nth weekday calculation in Python - whats wrong with this code?

I'm trying to calculate the nth weekday for a given date. For example, I should be able to calculate the 3rd wednesday in the month for a given date.
I have written 2 versions of a function that is supposed to do that:
from datetime import datetime, timedelta
### version 1
def nth_weekday(the_date, nth_week, week_day):
temp = the_date.replace(day=1)
adj = (nth_week-1)*7 + temp.weekday()-week_day
return temp + timedelta(days=adj)
### version 2
def nth_weekday(the_date, nth_week, week_day):
temp = the_date.replace(day=1)
adj = temp.weekday()-week_day
temp += timedelta(days=adj)
temp += timedelta(weeks=nth_week)
return temp
Console output
# Calculate the 3rd Friday for the date 2011-08-09
x=nth_weekday(datetime(year=2011,month=8,day=9),3,4)
print 'output:',x.strftime('%d%b%y')
# output: 11Aug11 (Expected: '19Aug11')
The logic in both functions is obviously wrong, but I can't seem to locate the bug - can anyone spot what is wrong with the code - and how do I fix it to return the correct value?
Your problem is here:
adj = temp.weekday()-week_day
First of all, you are subtracting things the wrong way: you need to subtract the actual day from the desired one, not the other way around.
Second, you need to ensure that the result of the subtraction is not negative - it should be put in the range 0-6 using % 7.
The result:
adj = (week_day - temp.weekday()) % 7
In addition, in your second version, you need to add nth_week-1 weeks like you do in your first version.
Complete example:
def nth_weekday(the_date, nth_week, week_day):
temp = the_date.replace(day=1)
adj = (week_day - temp.weekday()) % 7
temp += timedelta(days=adj)
temp += timedelta(weeks=nth_week-1)
return temp
>>> nth_weekday(datetime(2011,8,9), 3, 4)
datetime.datetime(2011, 8, 19, 0, 0)
one-liner
You can find the nth weekday with a one liner that uses calendar from the standard library.
import calendar
calendar.Calendar(x).monthdatescalendar(year, month)[n][0]
where:
x : the integer representing your weekday (0 is Monday)
n : the 'nth' part of your question
year, month : the integers year and month
This will return a datetime.date object.
broken down
It can be broken down this way:
calendar.Calendar(x)
creates a calendar object with weekdays starting on your required weekday.
.monthdatescalendar(year, month)
returns all the calendar days of that month.
[n][0]
returns the 0 indexed value of the nth week (the first day of that week, which starts on the xth day).
why it works
The reason for starting the week on your required weekday is that by default 0 (Monday) will be used as the first day of the week and if the month starts on a Wednesday, calendar will consider the first week to start on the first occurrence of Monday (ie. week 2) and you'll be a week behind.
example
If you were to need the third Saturday of September 2013 (that month's US stock option expiry day), you would use the following:
calendar.Calendar(5).monthdatescalendar(2013,9)[3][0]
The problem with the one-liner with the most votes is it doesn't work.
It can however be used as a basis for refinement:
You see this is what you get:
c = calendar.Calendar(calendar.SUNDAY).monthdatescalendar(2018, 7)
for c2 in c:
print(c2[0])
2018-07-01
2018-07-08
2018-07-15
2018-07-22
2018-07-29
c = calendar.Calendar(calendar.SUNDAY).monthdatescalendar(2018, 8)
for c2 in c:
print(c2[0])
2018-07-29
2018-08-05
2018-08-12
2018-08-19
2018-08-26
If you think about it it's trying to organise the calendars into nested lists to print a weeks worth of dates at a time. So stragglers from other months come into play. By using a new list of valid days that fall in the month - this does the trick.
Answer with appended list
import calendar
import datetime
def get_nth_DOW_for_YY_MM(dow, yy, mm, nth) -> datetime.date:
#dow - Python Cal - 6 Sun 0 Mon ... 5 Sat
#nth is 1 based... -1. is ok for last.
i = -1 if nth == -1 or nth == 5 else nth -1
valid_days = []
for d in calendar.Calendar(dow).monthdatescalendar(yy, mm):
if d[0].month == mm:
valid_days.append(d[0])
return valid_days[i]
So here's how it could be called:
firstSundayInJuly2018 = get_nth_DOW_for_YY_MM(calendar.SUNDAY, 2018, 7, 1)
firstSundayInAugust2018 = get_nth_DOW_for_YY_MM(calendar.SUNDAY, 2018, 8, 1)
print(firstSundayInJuly2018)
print(firstSundayInAugust2018)
And here is the output:
2018-07-01
2018-08-05
get_nth_DOW_for_YY_MM() can be refactored using lambda expressions like so:
Answer with lambda expression refactoring
import calendar
import datetime
def get_nth_DOW_for_YY_MM(dow, yy, mm, nth) -> datetime.date:
#dow - Python Cal - 6 Sun 0 Mon ... 5 Sat
#nth is 1 based... -1. is ok for last.
i = -1 if nth == -1 or nth == 5 else nth -1
return list(filter(lambda x: x.month == mm, \
list(map(lambda x: x[0], \
calendar.Calendar(dow).monthdatescalendar(yy, mm) \
)) \
))[i]
The one-liner answer does not seem to work if the target day falls on the first of the month. For instance, if you want the 2nd Friday of every month, then the one-liner approach
calendar.Calendar(4).monthdatescalendar(year, month)[2][0]
for March 2013 will return March 15th 2013 when it should be March 8th 2013. Perhaps add in a check like
if date(year, month, 1).weekday() == x:
delivery_date.append(calendar.Calendar(x).monthdatescalendar(year, month)[n-1][0])
else:
delivery_date.append(calendar.Calendar(x).monthdatescalendar(year, month)[n][0])
Alternatively this will work for Python 2, returns the occurance of weekday in the said month, i.e if 16 June 2018 is the input, then returns the occurance of the day on 16th June 2018
You may substitute the month/year/date integers to anything you might want - right now it's getting the input / date from the system via datetime
Omit out print statements or use pass where they're not needed
import calendar
import datetime
import pprint
month_number = int(datetime.datetime.now().strftime('%m'))
year_number = int(datetime.datetime.now().strftime('%Y'))
date_number = int(datetime.datetime.now().strftime('%d'))
day_ofweek = str(datetime.datetime.now().strftime('%A'))
def weekday_occurance():
print "\nFinding current date here\n"
for week in xrange(5):
try:
calendar.monthcalendar(year_number, month_number)[week].index(date_number)
occurance = week + 1
print "Date %s of month %s and year %s is %s #%s in this month." % (date_number,month_number,year_number,day_ofweek,occurance)
return occurance
break
except ValueError as e:
print "The date specified is %s which is week %s" % (e,week)
myocc = weekday_occurance()
print myocc
A little tweak would make the one-liner work correctly:
import calendar
calendar.Calendar((weekday+1)%7).monthdatescalendar(year, month)[n_th][-1]
Here n_th should be interpreted as c-style, e.g. 0 is the first index.
Example: to find 1st Sunday in July 2018 one could type:
>>> calendar.Calendar(0).monthdatescalendar(2018, 7)[0][-1]
datetime.date(2018, 7, 1)
People here seem to like one-liner, I will propose below.
import calendar
[cal[0] for cal in calendar.Calendar(x).monthdatescalendar(year, month) if cal[0].month == month][n]
The relativedelta module that's an extension from the Python dateutil package (pip install python-dateutil) does exactly what you want:
from dateutil import relativedelta
import datetime
def nth_weekday(the_date, nth_week, week_day):
return the_date.replace(day=1) + relativedelta.relativedelta(
weekday=week_day(nth_week)
)
print(nth_weekday(datetime.date.today(), 3, relativedelta.FR))
The key part here evaluates to weekday=relativedelta.FR(3): the third Friday of the month. Here are the relevant part of the docs for the weekday parameter,
weekday:
One of the weekday instances (MO, TU, etc) available in the
relativedelta module. These instances may receive a parameter N,
specifying the Nth weekday, which could be positive or negative
(like MO(+1) or MO(-2)).

Categories