如何在python中获取当前月份的最后一个星期三?
Posted
技术标签:
【中文标题】如何在python中获取当前月份的最后一个星期三?【英文标题】:How to get last wednesday for current month in python? 【发布时间】:2022-01-19 06:23:55 【问题描述】:我的代码如下
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
【问题讨论】:
通用算法:获取当月的第一个星期三+1,然后减去7天。 【参考方案1】:这是一种方法:
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)
【讨论】:
我尝试了上面的代码,但出现以下错误Traceback (most recent call last): File "E:\nifty_banknifty\banknifty_nifty_2018\bnf_nf_2018.py", line 141, in <module> todayDT += timedelta(days=1) OverflowError: date value out of range
@Adedoyin Akande
刚刚编辑,有错别字
现在上面的代码正在工作我得到nWed= 2018-03-28 00:00:00
这个输出。我怎样才能将2018-03-28
从上面的日期时间对象中分离出来? @Adedoyin Akande @AdedoyinAkande
我明白了!当我做nWed = nWed.date()
时,我得到nWed= 2018-03-28
这个日期是分开的。谢谢!!!
太棒了!您也可以为答案投票:winks【参考方案2】:
您可以结合使用日期时间和日历模块:
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_)
【讨论】:
感谢您接受我的建议。虽然这不是我应该做的那样,但当一个简单的数学可以做同样的事情时,我讨厌迭代。【参考方案3】:这个怎么样,我们先跳到下个月,重用你现有的代码:
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
【讨论】:
我试过上面的代码我得到以下错误Traceback (most recent call last): File "E:\nifty_banknifty\banknifty_nifty_2018\bnf_nf_2018.py", line 136, in <module> d = d + dt.timedelta(days=7) # so we are sure d is in the next month AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
@AlexKong @Alex Kong
您需要注意导入,如果您将我的代码复制并粘贴到新文件中,它应该可以工作——因为我可以获得正确的结果。以上是关于如何在python中获取当前月份的最后一个星期三?的主要内容,如果未能解决你的问题,请参考以下文章
java 给月份3月和该月1日是星期二,求该月最后一个工作日的日期 如何实现