![](/img/trans.png)
[英]Python: Return the date of the next occurence of a third Thursday of the month
[英]How to get last Thursday date of next month and next of next month using python
我想在下个月的最后一个星期四和下个月的下一个星期四获得日期。 目前能够获取当月最后一个星期四的日期。
代码:
import datetime
dt = datetime.datetime.today()
def lastThurs_currentmonth(dt):
currDate, currMth, currYr = dt, dt.month, dt.year
for i in range(31):
if currDate.month == currMth and currDate.year == currYr and currDate.weekday() == 3:
#print('dt:'+ str(currDate))
lastThuDate = currDate
currDate += datetime.timedelta(1)
return lastThuDate
lastThurs_currentmonth(dt)
Output:
datetime.datetime(2022, 11, 24, 11, 2, 17, 620842)
现在我需要在下个月和下个月的上周四约会。
预计 Output:
下个月上周四的日期
datetime.datetime(2022, 12, 29)
上周四为下个月下个月的日期
datetime.datetime(2023, 1, 26)
参考链接: 使用 python 获取当月的最后一个星期四
一种方法是从当月开始时将月数减去一天,然后再减去最后一个星期四。 星期四是 isoweekday 4,所以这是减去正确天数的情况。 不幸的是timedelta
不允许几个月,所以我的解决方案也需要dateutil
库。
import datetime
from dateutil.relativedelta import relativedelta
def last_thrs(start_date, months):
date_to_check = datetime.date(start_date.year, start_date.month, 1) + relativedelta(months=months+1) - datetime.timedelta(days=1)
return date_to_check - datetime.timedelta(days = ((date_to_check.isoweekday() + 3) % 7))
dt_today = datetime.date.today()
print(last_thrs(dt_today, 1))
# 2022-12-29
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.