需要在 python 中获取给定月份的最后一个星期四的日期



需要确定任何给定月份的最后一个星期四。如果给定的月份是当前月份,并且最后一个星期四已经过去了,则需要引发异常。我正在尝试使用datetime模块,但找不到简单的方法。

编辑:似乎我的问题不够清楚。我正在寻找的函数将返回给定月份最后一个星期四的日期,这样该月中返回日期之后的任何日期都不应是星期四。这个问题似乎已经被CrackaJackDev和af3ld有效地解决了。谢谢你。也非常感谢Bahrom的关键编辑和更正。我是这个社区的新手,如果我的问题组织得不好,很抱歉。下次我会更加努力的。

对于您问题的第一部分,我喜欢 date.utils 库中的相对三角洲。

from datetime import date
from dateutil.relativedelta import relativedelta, TH
def get_thurs(dt):
    print (dt + relativedelta(day=31, weekday=TH(-1)))
get_thurs(date(2016, 7, 7))
get_thurs(date(2019, 6, 4))

2016-07-28
2019-06-27

对于第二部分,我认为你想要这样的东西:

def get_thurs(dt):
    return (dt + relativedelta(day=31, weekday=TH(-1)))

def later_date(dt):
    if dt.month == date.today().month:  # checks if in current month
        if get_thurs(dt).day > dt.day:  # checks if last Thurs has passed
            raise Exception
        else:
            print "It is before that Thursday"

later_date(date(2016, 7, 23))
later_date(date(2016, 7, 29))

It is before that Thursday
Traceback (most recent call last):
  File "calculator/bw_events_cookies/tests/ideas.py", line 31, in <module>
    later_date(date(2016, 7, 23))
  File "calculator/bw_events_cookies/tests/ideas.py", line 26, in later_date
    raise Exception
Exception

这是一个不依赖于任何外部包的版本:

import datetime, calendar
def LastThInMonth(year, month):
    # Create a datetime.date for the last day of the given month
    daysInMonth = calendar.monthrange(year, month)[1]   # Returns (month, numberOfDaysInMonth)
    dt = datetime.date(year, month, daysInMonth)
    # Back up to the most recent Thursday
    offset = 4 - dt.isoweekday()
    if offset > 0: offset -= 7                          # Back up one week if necessary
    dt += datetime.timedelta(offset)                    # dt is now date of last Th in month
    # Throw an exception if dt is in the current month and occurred before today
    now = datetime.date.today()                         # Get current date (local time, not utc)
    if dt.year == now.year and dt.month == now.month and dt < now:
        raise Exception('Oops - missed the last Thursday of this month')
    return dt
for month in range(1, 13): print(LastThInMonth(2016, month))
2016-01-28
2016-02-25
2016-03-31
2016-04-28
2016-05-26
2016-06-30
2016-07-28
2016-08-25
2016-09-29
2016-10-27
2016-11-24
2016-12-29

略有不同的 aprroach:

import datetime
import calendar
def GetLastWeekdayOfMonth(year,month,weekday):
        lastDayOfMonth = datetime.datetime(year,month,calendar.monthrange(year,month)[1]) 
        
while lastDayOfMonth.weekday() != weekday:
            lastDayOfMonth-=datetime.timedelta(days=1)
        return lastDayOfMonth

对我来说效果很好!

另一种无需安装外部软件包的方法:

import datetime as dt
import calendar  
td = dt.date(2021,8,5)
monthlength = calendar.monthrange(td.year, td.month)[1]
expdate = dt.date(td.year, td.month, monthlength)
while True:
    expdate = expdate - dt.timedelta(1)
    if expdate.weekday() == 3:          # 3 is thursday
        break
print(expdate)

此函数将返回给定月份最后一个星期四日期的"YYYY-mm-dd"字符串,要引发异常,您可以解析日期并与当前日期进行比较。

import calendar 
def last_thursday_date(year, month):
    cal = calendar.monthcalendar(year, month)
    last_thurs_date = cal[4][3]
    if month < 10:
        thurday_date = str(year)+'-0'+ str(month)+'-' + str(last_thurs_date)
    else:
        thurday_date = str(year) + '-' + str(month) + '-' + str(last_thurs_date)
    return thurday_date

相关内容

  • 没有找到相关文章

最新更新