Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: weekday position of following months

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)?

like image 914
Tiago Moutinho Avatar asked Aug 11 '11 12:08

Tiago Moutinho


People also ask

How do I use weekday function in Python?

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.

How do I get the last day of the next month in Python?

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.

What week of the month is it Python?

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 .


2 Answers

Take a look at the datetime module. Specifically the weekday method of the date object. isocalendar might be helpful too.

like image 154
nmichaels Avatar answered Oct 24 '22 21:10

nmichaels


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.

like image 22
Sven Marnach Avatar answered Oct 24 '22 22:10

Sven Marnach