Given a date, how do you know the weekday position in the month (ex: third tuesday of the month) and how do you get the date for the same weekday for the next month (ex: third tuesday of the month+1)?
Use the weekday() method The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday. So its weekday number is 0.
Method #1 : Using replace() + timedelta() In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.
The answer you are looking for is (dm-dw+(dw-dm)%7)/7+1 where dm is the day of the month, dw is the day of the week, and % is the positive remainder. As dm and dw are always paired, these can be offset by any amount, so, switching everything to start a 1 only changes the the equation to (dm-dw + (dw-dm)%7)/7 + 1 .
Take a look at the datetime module. Specifically the weekday method of the date object. isocalendar might be helpful too.
In the examples below, d
is a datetime.date
object.
To get the "index" of the day within the current month, use
def weekday_index(d):
return (d.day + 6) // 7
This formula will work independent of what weekday the date actually is. To get the day wich is the same weekday with the same weekday index within the next month, the simplest way seems to be
d_next = d + datetime.timedelta(weeks=4)
if weekday_index(d_next) < weekday_index(d):
d_next += datetime.timedelta(weeks=1)
This uses the fact the the date you are looking for is either 4 weeks or 5 weeks after d
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With