Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding last business day of a month in python

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!

like image 689
tkyass Avatar asked May 25 '16 15:05

tkyass


People also ask

How do I get the last weekday of the month in Python?

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.

How do you check business days in Python?

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.

How do I find previous business days?

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.


2 Answers

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)
like image 173
Elke Avatar answered Oct 04 '22 21:10

Elke


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')
like image 37
nyan314sn Avatar answered Oct 04 '22 22:10

nyan314sn