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)?
Asked
Active
Viewed 682 times
5
-
You've already asked two other questions about relative dates and have received plenty of helpful information; you should be able to figure this out from those answers. – eric Aug 11 '11 at 12:45
4 Answers
3
Take a look at the datetime module. Specifically the weekday method of the date object. isocalendar might be helpful too.

nmichaels
- 49,466
- 12
- 107
- 135
2
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
.

Sven Marnach
- 574,206
- 118
- 941
- 841
1
import datetime
cnt=1
d=datetime.datetime.now()
d1=datetime.datetime(d.year,d.month,1,d.hour,d.minute,d.second,d.microsecond)
while(d1.day!=d.day):
if 6-d1.weekday()==1:cnt=cnt+1
d1=d1+datetime.timedelta(days=1)
print cnt #print current date week position

ravikanth
- 11
- 1