Frash Frash - 1 year ago 130
Python Question

Get the last thursday of the current month using python

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 =
cmon = todayte.month

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

Answer Source

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 =
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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download