user2379701 user2379701 - 4 months ago 9
Python Question

Need to get date of last Thursday of a given month in python?

Need to determine any given month's last Thursday. If given month is current month, and the last Thursday has passed, need to raise an exception. I am trying to use

datetime
module, but can't find a straightforward way of doing this.

Edit: seems like my question was not clear enough. The function I am looking for will return the date of the final Thursday of a given month, such that no date following the returned date in the month shall be a Thursday. The problem seems to have been effectively solved by CrackaJackDev and af3ld. Thank you for that. Also a big thanks to Bahrom for crucial edits and correction. I am new to this community, so sorry if my question was not well organized. I shall try harder next time.

Answer

Here's a version that doesn't depend on any external packages:

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
Comments