I'm trying to find last business day of of the month. I wrote the code below for that and it works fine but I was wondering if there is a cleaner way of doing it?
from datetime import date,timedelta
import datetime
import calendar
today=datetime.date.today()
last = today.replace(day=calendar.monthrange(today.year,today.month)[1])
if last.weekday()<5:
print last
else:
print last-timedelta(days=1+last.weekday()-5)
Thanks in advance!
In this, we perform the task of getting each month calendar using monthcalendar() from the calendar library. Each weekday date is extracted and the maximum of it, being the maximum of the whole month is the last weekday, hence extracted.
Use the import numpy as np statement to import the numpy module in your Python file. Create a start date and end date using the datetime. date() class of a datetime module. The busday_count() function counts the number of business days between the start date and end date, not including the day of the end dates.
The previous business day is the most recent prior day on which banks were open for business. Business days are Monday through Friday, not including holidays. For example, on a Tuesday, you would see Monday's transactions. On a Monday, you would see the previous Friday's transactions.
I use the following:
from pandas.tseries.offsets import BMonthEnd
from datetime import date
d=date.today()
offset = BMonthEnd()
#Last day of current month
offset.rollforward(d)
#Last day of previous month
offset.rollback(d)
Let's say you want to get the last business days of the month up-to the end of the next two years, the following will work.
import pandas as pd
import datetime
start = datetime.date.today()
end = datetime.date(start.year+2, 12, 31)
bussiness_days_rng =pd.date_range(start, end, freq='BM')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With