In [1]:
import calendar
import datetime
In [2]:
print(calendar.month(2019, 1))
In [3]:
def get_nth_week(day):
return (day - 1) // 7 + 1
In [4]:
def get_nth_dow(year, month, day):
return get_nth_week(day), calendar.weekday(year, month, day)
In [5]:
print(get_nth_dow(2019, 1, 7))
In [6]:
print(get_nth_dow(2019, 1, 20))
In [7]:
def get_nth_dow_datetime(year, month, day):
return get_nth_week(day), datetime.date(year, month, day).weekday()
In [8]:
print(get_nth_dow_datetime(2019, 1, 7))
In [9]:
print(get_nth_dow_datetime(2019, 1, 20))
In [10]:
def get_nth_dow_datetime_dt(dt):
return get_nth_week(dt.day), dt.weekday()
In [11]:
dt = datetime.datetime(2019, 1, 20)
print(get_nth_dow_datetime_dt(dt))
In [12]:
d = datetime.date(2019, 1, 20)
print(get_nth_dow_datetime_dt(d))
In [13]:
print(datetime.date.today())
In [14]:
print(get_nth_dow_datetime_dt(datetime.date.today()))
In [15]:
print(calendar.month(2019, 1))
In [16]:
calendar.setfirstweekday(6)
print(calendar.month(2019, 1))
In [17]:
def get_nth_week2(year, month, day, firstweekday=0):
first_dow = calendar.monthrange(year, month)[0]
offset = (first_dow - firstweekday) % 7
return (day + offset - 1) // 7 + 1
In [18]:
print(get_nth_week2(2019, 1, 20))
In [19]:
print(get_nth_week2(2019, 1, 20, 6))
In [20]:
def get_nth_week2_datetime(year, month, day, firstweekday=0):
first_dow = datetime.date(year, month, 1).weekday()
offset = (first_dow - firstweekday) % 7
return (day + offset - 1) // 7 + 1
In [21]:
print(get_nth_week2_datetime(2019, 1, 20))
In [22]:
print(get_nth_week2_datetime(2019, 1, 20, 6))
In [23]:
def get_nth_week2_datetime_dt(dt, firstweekday=0):
first_dow = dt.replace(day=1).weekday()
offset = (first_dow - firstweekday) % 7
return (dt.day + offset - 1) // 7 + 1
In [24]:
dt = datetime.datetime(2019, 1, 20)
print(get_nth_week2_datetime_dt(dt))
In [25]:
print(get_nth_week2_datetime_dt(dt, 6))
In [26]:
d = datetime.date(2019, 1, 20)
print(get_nth_week2_datetime_dt(d))
In [27]:
print(get_nth_week2_datetime_dt(d, 6))
In [28]:
print(datetime.date.today())
In [29]:
print(get_nth_week2_datetime_dt(datetime.date.today()))
In [30]:
print(get_nth_week2_datetime_dt(datetime.date.today(), 6))