Search code examples
python-3.xtime-seriespython-datetimetimedelta

How to get last wednesday for current month in python?


my code as follows

today = todayte
print('today1 =', today)
offset = (today.weekday() - 2) % 7
print('offset1=', offset)
last_wednesday = today - timedelta(days=offset)            
print('last_wednesday1 = ', last_wednesday)

my current output as follows

today1 = 2018-03-05
offset1 = 5
last_wednesday1 =  2018-02-28

in the above case i am getting previous month last wednesday
but i need current month last wednesday.

my expected output is as follows

last_wednesday = 2018-03-28

Solution

  • Here is a way:

    from datetime import datetime , timedelta
    
    todayDT = datetime.today()
    currentMonth = todayDT.month
    
    nWed = todayDT
    while todayDT.month == currentMonth:
        todayDT += timedelta(days=1)
        if todayDT.weekday()==2: #this is Wednesday 
            nWed = todayDT
    print (nWed)