Home > Software design >  How to get last Thursday date of next month and next of next month using python
How to get last Thursday date of next month and next of next month using python

Time:11-20

I want to get Date on Last Thursday of next month and next of next month. Currently able to get Date of last thursday on current month.

Code:

import datetime
dt = datetime.datetime.today()
def lastThurs_currentmonth(dt):
    currDate, currMth, currYr = dt, dt.month, dt.year
    for i in range(31):
        if currDate.month == currMth and currDate.year == currYr and currDate.weekday() == 3:
            #print('dt:'  str(currDate))
            lastThuDate = currDate
        currDate  = datetime.timedelta(1)

    return lastThuDate
lastThurs_currentmonth(dt)

Output:

datetime.datetime(2022, 11, 24, 11, 2, 17, 620842)

Now I need to get date last Thursday for next month and next of next month.

Expected Output:

date last Thursday for next month

datetime.datetime(2022, 12, 29)

date last Thursday for next of next month

datetime.datetime(2023, 1, 26)

Ref link: Get the last thursday of the current month using python

CodePudding user response:

One way is to add months less one day from the start of the current month and then subtract back to the last Thursday. Thursdays are isoweekday 4, so it's a case of subtracting off the right number of days. Unfortunately timedelta doesn't allow months, so the dateutil library is also needed for my solution.

import datetime
from dateutil.relativedelta import relativedelta

def last_thrs(start_date, months):
    date_to_check = datetime.date(start_date.year, start_date.month, 1)   relativedelta(months=months 1) - datetime.timedelta(days=1)
    return date_to_check - datetime.timedelta(days = ((date_to_check.isoweekday()   3) % 7))


dt_today = datetime.date.today()
print(last_thrs(dt_today, 1))
# 2022-12-29
  • Related