使用python获取当月的最后一个星期四

问题描述 投票:0回答:12

按照这个答案,我试图获取当月最后一个星期四的日期。但我的代码没有脱离循环。

from datetime import datetime
from dateutil.relativedelta import relativedelta, TH

todayte = datetime.today()
cmon = todayte.month

nthu = todayte
while nthu.month == cmon:
    nthu += relativedelta(weekday=TH(1))
    #print nthu.strftime('%d%b%Y').upper()
python datetime python-dateutil
12个回答
5
投票

查看

relativedelta

的文档

请注意,如果计算出的日期已经是

Monday
,例如,使用
(0, 1)
(0, -1)
不会更改日期。

如果

nthu
已经是星期四,那么添加
TH(1)
TH(-1)
不会产生任何效果,但会产生相同的日期,这就是循环无限运行的原因。

我假设一个月最多 5 周,并按照以下方式进行:

todayte = datetime.today()
cmon = todayte.month

for i in range(1, 6):
    t = todayte + relativedelta(weekday=TH(i))
    if t.month != cmon:
        # since t is exceeded we need last one  which we can get by subtracting -2 since it is already a Thursday.
        t = t + relativedelta(weekday=TH(-2))
        break

3
投票

根据 Adam Smith 对 How can I get the 3rd Friday of a Month in Python? 的回答,您可以获取当月最后一个星期四的日期,如下所示:

import calendar
import datetime

def get_thursday(cal,year,month,thursday_number):
    '''
    For example, get_thursday(cal, 2017,8,0) returns (2017,8,3) 
    because the first thursday of August 2017 is 2017-08-03
    '''
    monthcal = cal.monthdatescalendar(year, month)
    selected_thursday = [day for week in monthcal for day in week if \
                    day.weekday() == calendar.THURSDAY and \
                    day.month == month][thursday_number]
    return selected_thursday

def main():
    '''
    Show the use of get_thursday()
    '''
    cal = calendar.Calendar(firstweekday=calendar.MONDAY)
    today = datetime.datetime.today()
    year = today.year
    month = today.month
    date = get_thursday(cal,year,month,-1) # -1 because we want the last Thursday 
    print('date: {0}'.format(date)) # date: 2017-08-31        

if __name__ == "__main__":
    main()

3
投票

你可以这样做:

import pandas as pd
from dateutil.relativedelta import relativedelta, TH

expiry_type = 0
today = pd.datetime.today()
expiry_dates = []

if expiry_type == 0:
    # Weekly expiry
    for i in range(1,13):
         expiry_dates.append((today + relativedelta(weekday=TH(i))).date())
else:
    # Monthly expiry
    for i in range(1,13):
        x = (today + relativedelta(weekday=TH(i))).date()
        y = (today + relativedelta(weekday=TH(i+1))).date()
        if x.month != y.month :
            if x.day > y.day :
                expiry_dates.append(x)

print(expiry_dates)

1
投票

您应该将 2 传递给

TH
而不是 1,因为 1 不会改变任何内容。将您的代码修改为:

while (nthu + relativedelta(weekday=TH(2))).month == cmon:
    nthu += relativedelta(weekday=TH(2))

print nthu.strftime('%d-%b-%Y').upper()
# prints 26-MAY-2016

请注意,我修改了循环的条件,以便在当月最后一次出现时中断,否则它将在下个月(在本例中为六月)中断。


1
投票
from datetime import datetime , timedelta

todayte = datetime.today()
cmon = todayte.month

nthu = todayte
while todayte.month == cmon:
    todayte += timedelta(days=1)
    if todayte.weekday()==3: #this is Thursday 
        nthu = todayte
print nthu

1
投票

您还可以使用

calendar
包。 以
monthcalendar
的形式访问日历。请注意,星期五是一周的最后一天。

import calendar
import datetime
now = datetime.datetime.now()
last_sunday = max(week[-1] for week in calendar.monthcalendar(now.year,
                                                              now.month))
print('{}-{}-{:2}'.format(now.year, calendar.month_abbr[now.month],
                              last_sunday))

1
投票

我认为这可能是最快的:

end_of_month = datetime.datetime.today() + relativedelta(day=31)
last_thursday = end_of_month + relativedelta(weekday=TH(-1))

1
投票

此代码可在 python 3.x 中用于查找当月的最后一个星期四。

import datetime
dt = datetime.datetime.today()
def lastThurs(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

0
投票
import datetime
def get_thursday(_month,_year):
    for _i in range(1,32):
        if _i > 9:
            _dateStr = str(_i)
        else:
            _dateStr = '0' + str(_i)
        _date = str(_year) + '-' + str(_month) + '-' + _dateStr
        try:
            a = datetime.datetime.strptime(_date, "%Y-%m-%d").strftime('%a')
        except:
             continue
        if a == 'Thu':
            _lastThurs = _date
    return _lastThurs

x = get_thursday('05','2017')
print(x)

0
投票

它是快速且易于理解,我们取每个月的第一天,然后将其减去3,因为3是星期四工作日的数字,然后将其乘以4,然后检查它是否在同一个月,如果是的话那么那就是上周四,否则我们将其乘以 3,就得到了最后周四

import datetime as dt

from datetime import timedelta

#start is the first of every month

start = dt.datetime.fromisoformat('2022-08-01')

if start.month == (start + timedelta((3 - start.weekday()) + 4*7)).month:

  exp = start + timedelta((3 - start.weekday()) + 4*7)

else:

  exp = start + timedelta((3 - start.weekday()) + 3*7)

0
投票

您可以使用日历来实现您的结果。我觉得很简单。

import calendar
import datetime

testdate= datetime.datetime.now()
weekly_thursday=[]
for week in calendar.monthcalendar(testdate.year,testdate.month):
    if week[3] != 0:
        weekly_thursday.append(week[3])
weekly_thursday

列表 week_thursday 将包含该月的所有星期四。

weekly_thursday[-1]
将为您提供该月的最后一个星期四。


testdate : datetime.datetime(2022, 9, 9, 6, 35, 16, 752465)
weekly_thursday : [1, 8, 15, 22, 29]
weekly_thursday [-1]:29

0
投票

这对我有用:

import calendar 
import pandas as pd
 
a_day = pd.Timestamp.now().date() 
day_1, x_days = calendar.monthrange(a_day.year, a_day.month)
 
Thurs = 3 # Mon-Sun -> 0-6 
off_set = day_1 - Thur
last_Thurs = x_days + off_set 
print('The last Thursday is on the', last_Thurs)
© www.soinside.com 2019 - 2024. All rights reserved.