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

时间:2016-07-07 20:33:25

标签: python datetime

需要确定任何给定月份的上周四。如果给定月份是当前月份,并且最后一个星期四已经过去,则需要提出异常。我正在尝试使用datetime模块,但无法找到一种直接的方法。

编辑:好像我的问题不够明确。我正在寻找的功能将返回给定月份的最后一个星期四的日期,这样在该月份的返回日期之后的日期不应该是星期四。这个问题似乎已经被CrackaJackDev和af3ld有效地解决了。谢谢你。同样非常感谢Bahrom的重要编辑和修正。我是这个社区的新手,很抱歉,如果我的问题没有得到很好的组织。我下次会更加努力。

5 个答案:

答案 0 :(得分:2)

对于问题的第一部分,我喜欢date.utils库中的relativedelta

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

此函数将返回给定月份的最后一个星期四的日期的'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

答案 3 :(得分:0)

略有不同的方法:

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

对我来说做得很好!

答案 4 :(得分:0)

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

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)