user2379701 user2379701 - 1 year ago 48
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

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 Source

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

import datetime, calendar

def LastThInMonth(year, month):
    # Create a for the last day of the given month
    daysInMonth = calendar.monthrange(year, month)[1]   # Returns (month, numberOfDaysInMonth)
    dt =, 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 =                         # 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))