Zack
Zack

Reputation: 349

find the last business date for June and Dec of any given year in Python

I want to find the last business day for the month of June and Dec for 2019. my below code gives me the last business day for last month and the current month. Ideally i want a code which allows me to input a year and month and it will tell me the last business day for the month and year i input.

i want my output to be like this for June 2019 and Dec 2019

2906 3112

hope someone can help me here, thanks

from pandas.tseries.offsets import BMonthEnd
from datetime import date

d=date.today()

offset = BMonthEnd()

#Last day of current month
current_month = offset.rollforward(d)
print(current_month)

#Last day of previous month
last_month = offset.rollback(d)
print(last_month)

Upvotes: 1

Views: 278

Answers (1)

Kyle Willmon
Kyle Willmon

Reputation: 719

Here's a function that will find the last weekday in a given month and format it as a string in the format given

import datetime

def last_weekday(year, month):
    # Add a month
    if month == 12:
        month = 1
        year += 1
    else:
        month += 1

    d = datetime.date(year, month, 1)

    # Subtract a day
    d -= datetime.timedelta(days=1)

    # Subtract more days if we have a weekend
    while d.weekday() >= 5:
        d -= datetime.timedelta(days=1)

    return '{:02d}{:02d}'.format(d.month, d.day)

# Examples:
last_weekday(2019, 6)  # -> '0628'
last_weekday(2019, 12) # -> '1231'

Upvotes: 1

Related Questions