如何获取 python 本月的最后一个星期三?

How to get last wednesday for current month in python?

我的代码如下

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

我目前的输出如下

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

在上述情况下,我得到 上个月上周三
但我 需要上周三当月的数据。

我的预期输出如下

last_wednesday = 2018-03-28

这里有一个方法:

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)

怎么样,我们先跳转到下个月,重新使用您现有的代码:

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)

结果:

2018-04-04

您可以结合使用日期时间和日历模块:

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)

@Mark Ransom建议:

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_)