Python: position on weekdays of the following months

Given the date, how do you know the position of the day of the week in the month (for example, the third Tuesday of the month) and how do you get the date for the same day of the week for the next month (for example: the third Tuesday of the month + 1)?

+5
source share
4 answers

In the examples below, dis an object datetime.date.

To get the "index" of the day in the current month, use

def weekday_index(d):
    return (d.day + 6) // 7

This formula will work no matter what day of the week it really is. To get a day that is the same day of the week with the same weekday index for the next month, the easiest way is

d_next = d + datetime.timedelta(weeks=4)
if weekday_index(d_next) < weekday_index(d):
    d_next += datetime.timedelta(weeks=1)

, , , 4 5 d.

+2
+3

Take a look at dateutil

+2
source
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
+1
source

All Articles