Home > Back-end >  How to get last wednesday for current month in python?
How to get last wednesday for current month in python?

Time:12-16

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

CodePudding user response:

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)

CodePudding user response:

How about this, we first jump to the next month and re-use your existing code:

import datetime as dt

todayte = dt.date(2018, 3, 5)
today = todayte
d = dt.date(today.year, today.month, 28) # the 28th day of a month must exist
d = d   dt.timedelta(days=7) # so we are sure d is in the next month
# then we apply your original logic
offset = (d.weekday() - 2) % 7
last_wednesday = d - dt.timedelta(days=offset)
print(last_wednesday)

Result:

2018-04-04

CodePudding user response:

you can use a combination of datetime and calendar modules:

from datetime import datetime, timedelta
import calendar

today = datetime.now()
# find first day of the month and then, find first wednesday of the month and replace it
# weekday of wednesday == 2
first_day = datetime.today().replace(day=1)
while first_day.weekday() != 2:
    first_day  = timedelta(days=1)

number_of_days_in_month = calendar.monthrange(today.year, today.month)[1]
last_wend = first_day   timedelta(days=(((number_of_days_in_month - first_day.day) // 7) * 7))

print(last_wend)

or as @Mark Ransom suggested:

from datetime import datetime, timedelta

day_ = (datetime.now().replace(day=1)   timedelta(days=32)).replace(day=1)
while True:
    day_ -= timedelta(days=1)
    if day_.weekday() == 2:
        break
print(day_)
  • Related