6

Get the last Thursday of the current month using Python

 3 years ago
source link: https://www.codesd.com/item/get-the-last-thursday-of-the-current-month-using-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Get the last Thursday of the current month using Python

advertisements

Following this answer I tried to get the date for last Thursday of the current month. But my code doesn't get out of loop.

from datetime import datetime
from dateutil.relativedelta import relativedelta, TH

todayte = datetime.today()
cmon = todayte.month

nthu = todayte
while nthu.month == cmon:
    nthu += relativedelta(weekday=TH(1))
    #print nthu.strftime('%d%b%Y').upper()


Looking at the documentation of relativedelta

Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won’t change the day.

If nthu is already Thursday then adding TH(1) or TH(-1) won't have any effect but result in the same date and that's why your loop is running infinitely.

I will assume maximum 5 weeks in a month and do it like following:

todayte = datetime.today()
cmon = todayte.month

for i in range(1, 6):
    t = todayte + relativedelta(weekday=TH(i))
    if t.month != cmon:
        # since t is exceeded we need last one  which we can get by subtracting -2 since it is already a Thursday.
        t = t + relativedelta(weekday=TH(-2))
        break


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK