Python: Calculate the first/last Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday of the Month

4 comments
Date calculation is pretty easy in Python, but to find the first/last specific day of the month may be a bit harder.
import calendar

# Get the first "day" of the month and the number of days in the month
month_range = calendar.monthrange(your_date.year, your_date.month)

if offset_position == 'first': # First Monday of the month
date_corrected = datetime.date(your_date.year, your_date.month, 1)
delta = (calendar.MONDAY - month_range[0]) % 7
return your_date_corrected + datetime.timedelta(days = delta)

else: # Last Monday of the month
date_corrected = datetime.date(your_date.year, your_date.month, month_range[1])
delta = (your_date.weekday() - calendar.MONDAY) % 7
return your_date_corrected - datetime.timedelta(days = delta)

The snippet above will find the first or last Monday in the year/month given in "your_date". Throw it into a reusable function and you won't have to look at this problem again.
2n8n0x0
Now for more important things in life.

Sources

Related Posts

4 comments:

  1. i believe your calculation for finding the last specific day is wrong. you wanna use date_corrected when calculating delta and returning instead of your_date. that's what worked for me at least.

    ReplyDelete
  2. Oops! Yep you're right!
    I didn't rename the variables correctly when copying from my project src

    Thanks for that

    ReplyDelete
  3. http://stackoverflow.com/questions/12796389/python-get-last-monday-of-july-2010

    ReplyDelete

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog