How to calculate number of Mondays left in a month with Python - python

I'm building out a forecast model in Python and need to calculate the number of remaining days for each day name of a month. For example, on October 25, 2017 there are no remaining Wednesdays in the current month and there is 1 remaining Thursday, Friday, Saturday, Sunday, Monday, and Tuesday.
I'm able to achieve the same result in R with:
first <- as.Date(cut(Sys.Date(), "month"))
last <- as.Date(cut(first + 31, "month")) - 1
sum(format(seq(Sys.Date(), last, "day"), "%w") == 0) -> Sunday
I'm trying to edit the following code block which was initially intended to count weekdays in a month for my purposes but not sure if I'm on the right track
import calendar
weekday_count = 0
cal = calendar.Calendar()
for week in cal.monthdayscalendar(2013, 8):
for i, day in enumerate(week):
# not this month's day or a weekend
if day == 0 or i >= 5:
continue
# or some other control if desired...
weekday_count += 1
print(weekday_count)

You might want to use this as a starting point. It will calculate the number of remaining Mondays given a day, month, year of your choosing.
from datetime import datetime, timedelta
# Monday = 0
def get_remaining_mondays(year, month, day):
count = 0
try:
d = datetime(year, month, day)
wday = d.weekday()
d += timedelta(days=7 - wday)
while d.month == month:
count += 1
d += timedelta(days=7)
except ValueError as v:
return v
return count
print(get_remaining_mondays(2017, 11, 7))

Related

How to determine all the week numbers in a month with Python?

I have the following problem: Given a year and a month, determine the week numbers that are contained in that particular month, i.e., October 2017 contains week numbers 39,40,41,42,43,44. Caveat: As a rule, week starts in Monday and ends in Sunday. I have a cumbersome code that does the trick but I would like to know if there is a more elegant or Pythonistic way of doing this.
from datetime import datetime
import calendar
def get_week_numbers_in_month(year,month):
list_of_weeks = []
initial_day = 1
ending_day = calendar.monthrange(int(year),int(month))[1] #get the last day of month
initial_week = int(datetime(year,month,initial_day).isocalendar()[1])
ending_week = int(datetime(year,month,ending_day).isocalendar()[1])
counter = initial_week
while(counter <= ending_week):
list_of_weeks.append(counter)
counter += 1
return list_of_weeks
print("Your month contains the following weeks:\n"+str(get_week_numbers_in_month(2017,10)))
# result: Your month contains the following weeks:
# [39, 40, 41, 42, 43, 44]
You could simply return a range and avoid the whole initializing process. Also, note that isocalendar returns a 3-tuple of integers:
from datetime import datetime
import calendar
def get_week_numbers_in_month(year,month):
ending_day = calendar.monthrange(year, month)[1] #get the last day of month
initial_week = datetime(year, month, 1).isocalendar()[1]
ending_week = datetime(year, month, ending_day).isocalendar()[1]
return range(initial_week, ending_week + 1)
print("Your month contains the following weeks:")
print(get_week_numbers_in_month(2017,10))
# range(39, 45)
If you really want to return a list, simply return list(range(...))
My approach 😊
from datetime import datetime
import calendar
def get_week_numbers_in_month(year, month) -> list:
ending_day = calendar.monthrange(year, month)[1] # get the last day of month
initial_week = datetime(year, month, 1).isocalendar()[1]
ending_week = datetime(year, month, ending_day).isocalendar()[1]
res = list(range(initial_week, ending_week + 1))
if not res:
week_num = 52 if initial_week != 53 else 53
res = list(range(initial_week, week_num + 1)) + list(range(1, ending_week + 1))
return res
Output
>>> print(get_week_numbers_in_month(2021, 1))
[52, 1, 2, 3, 4]
>>>
I would have added this as a comment, but do not have enough reputation to do so...
It looks like the approved answer does not actually work for the month of December as it will sometimes spill over into week 1. Also, why is it adding a week to the end when it creates the range?
Accepted answer:
def get_week_numbers_in_month(year,month):
ending_day = calendar.monthrange(year, month)[1] #get the last day of month
initial_week = datetime(year, month, 1).isocalendar()[1]
ending_week = datetime(year, month, ending_day).isocalendar()[1]
return range(initial_week, ending_week + 1)
print(get_week_numbers_in_month(2019,12))
# range(48, 2)
print(list(get_week_numbers_in_month(2019,12)))
# []
You would actually need to add some additional logic to build the list yourself instead of using a range
def get_week_numbers_in_month(year,month):
ending_day = calendar.monthrange(year, month)[1] #get the last day of month
initial_week = datetime(year, month, 1).isocalendar()[1]
ending_week = datetime(year, month, ending_day).isocalendar()[1]
# Adding logic to build week list if month is December (12)
if month = 12:
week_list = []
while week != ending_week:
if week not in week_list:
week_list.append(week)
else:
if week >= 52:
week = 1
else:
week += 1
week_list.append(week)
else:
week_list = list(range(initial_week, ending_week))
return week_list
print(get_week_numbers_in_month(2019,12))
# [48, 49, 50, 51, 52, 1]

Determine current month variable that rolls over to next month after the 15th day- python 2.7

I use the current_month variable to query data but here's the catch- if the day in the month is later then the 15th, I want to set the current month to be the following month. So the current month for 4/16/2016 should be 5/1/2016. I've got code that works but it doesn't feel pythonic. Suggestions would be appreciated.
month = datetime.datetime.now().strftime("%m")
year = datetime.datetime.now().strftime("%Y")
day = datetime.datetime.now().strftime("%d")
#Check if day in the month is past 15th if so set current month
if int(day) > 15:
if int(month) < 9: # check if the month in 1-9 if so pad leading zero
x = int(month)+1
current_month = year+"-0"+str(x)+"-01"
if int(month) == 9: # check if the month in 1-9 if so pad leading zero
x = int(month)+1
current_month = year+"-"+str(x)+"-01"
elif int(month) == 12: # check if the month is Dec if so roll to the next year and set month to Jan
month = "01"
y = int(year)+1
current_month = str(y)+"-"+month+"-01"
else:
x = int(month)+1 # just add one to the month if months are 10 or 11
current_month = year+"-"+str(x)+"-01"
else:
current_month = year+"-"+month+"-01" #prior to the 15'th so just use normal year, month and day
# Get today's date/time
today = datetime.datetime.now()
# add 16 days if after the 15th
if today.day > 15:
today += datetime.timedelta(16)
# Format that date w/ day being 1
current_month = today.strftime("%Y-%m-01")
An alternative to Scott's approach (which works perfectly well and you should probably accept it) is to use a dateutil.relativedelta:
from datetime import datetime
from dateutil.relativedelta import relativedelta
def next_month_after_day(dt, trans_day=15):
rd = relativedelta(months=(dt.day > trans_day), day=1)
return dt + rd
dt1 = datetime(1996, 2, 3)
dt2 = datetime(1996, 2, 15)
dt3 = datetime(1996, 2, 16)
dt4 = datetime(1996, 12, 18)
fmt = "%Y-%m-%d"
for x in (dt1, dt2, dt3, dt4):
dt_before = x
dt_after = next_month_after_day(x)
print('{} -> {}'.format(dt_before.strftime(fmt), dt_after.strftime(fmt)))
The result is:
1996-02-03 -> 1996-02-01
1996-02-15 -> 1996-02-01
1996-02-16 -> 1996-03-01
1996-12-18 -> 1997-01-01
Thanks to Scott for pointing out why my original approach was needlessly complicated (and wrong).

Generate date ranges broken by month for a given period

I'm struggling with writing a pythonic, clean generator method that, given a date period, like ['2014-01-15', '2015-02-03], will give me this:
['2014-01-15', '2014-01-31']
['2014-02-01', '2014-02-28']
...
['2015-02-01', '2015-02-03']
This is what I came up with:
from datetime import datetime
import calendar
def genDatePeriods(startDate, endDate, format='%Y-%m-%d'):
dt1 = datetime.strptime(startDate, format)
dt2 = datetime.strptime(endDate, format)
for year in range(dt1.year, dt2.year + 1):
for month in range(1, 13):
day0 = dt1.day if month == dt1.month and year == dt1.year else 1
day1 = dt2.day if month == dt2.month and year == dt2.year else calendar.monthrange(year, month)[1]
if (year == dt1.year and month < dt1.month) or (year == dt2.year and month > dt2.month):
continue
else:
d0 = (year, month, day0)
d1 = (year, month, day1)
yield [datetime(*d).strftime(format) for d in [d0, d1]]
It works, however I feel like there is a more pythonic/tidy/efficient way to do this. Any ideas?
The following is much more concise, using datetime.date() objects to find the first day of the next month each time, until you reach the end date:
from datetime import datetime, timedelta
def genDatePeriods(startDate, endDate, format='%Y-%m-%d'):
curr = datetime.strptime(startDate, format).date()
end = datetime.strptime(endDate, format).date()
while curr <= end:
# first day of the next month, using modular arithmetic
next_month = curr.replace(
month=curr.month % 12 + 1, year=curr.year + curr.month // 12,
day=1)
curr_formatted = curr.strftime(format)
# end date is next month's first day, minus one day,
# or the given endDate, whichever comes first
end_formatted = min(next_month - timedelta(days=1), end).strftime(format)
yield [curr_formatted, end_formatted]
curr = next_month
Demo:
>>> for res in genDatePeriods('2014-01-15', '2015-02-03'):
... print res
...
['2014-01-15', '2014-01-31']
['2014-02-01', '2014-02-28']
['2014-03-01', '2014-03-31']
['2014-04-01', '2014-04-30']
['2014-05-01', '2014-05-31']
['2014-06-01', '2014-06-30']
['2014-07-01', '2014-07-31']
['2014-08-01', '2014-08-31']
['2014-09-01', '2014-09-30']
['2014-10-01', '2014-10-31']
['2014-11-01', '2014-11-30']
['2014-12-01', '2014-12-31']
['2015-01-01', '2015-01-31']
['2015-02-01', '2015-02-03']

How can I get the 3rd Friday of a month in Python?

I'm trying to get stock data from Yahoo! Finance using Python 2.7.9, but I only need data for the 3rd Friday of the month. I have a function to get the data, but need a way to get the dates. I want something like this:
def get_third_fris(how_many):
# code and stuff
return list_of_fris
So that calling get_third_fris(6) will return a 6-item-long list of 3rd Fridays following the current date. The dates need to be Unix timestamps.
(I have pretty much no experience with time or datetime, so please explain what your code is doing.)
Thanks!
You can use the calendar module to list weeks, then grab the Friday of that week.
import calendar
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2015; month = 2
monthcal = c.monthdatescalendar(year,month)
third_friday = [day for week in monthcal for day in week if \
day.weekday() == calendar.FRIDAY and \
day.month == month][2]
You can format to Unix timestamp, but it's non-trivial. I'll refer you to this excellent answer which has info based on whether or not your date is timezone-aware.
We do not need to import anything other than datetime. We can assume 7 days in a week and weekday 0 == Monday.
import datetime
def third_friday(year, month):
"""Return datetime.date for monthly option expiration given year and
month
"""
# The 15th is the lowest third day in the month
third = datetime.date(year, month, 15)
# What day of the week is the 15th?
w = third.weekday()
# Friday is weekday 4
if w != 4:
# Replace just the day (of month)
third = third.replace(day=(15 + (4 - w) % 7))
return third
Assuming you want a range of every 3rd Friday, you can just use pandas, sample code:
import pandas as pd
pd.date_range('2017-12-02','2020-08-31',freq='WOM-3FRI')
Output:
DatetimeIndex(['2017-12-15', '2018-01-19', '2018-02-16', '2018-03-16',
'2018-04-20', '2018-05-18', '2018-06-15', '2018-07-20',
'2018-08-17', '2018-09-21', '2018-10-19', '2018-11-16',
'2018-12-21', '2019-01-18', '2019-02-15', '2019-03-15',
'2019-04-19', '2019-05-17', '2019-06-21', '2019-07-19',
'2019-08-16', '2019-09-20', '2019-10-18', '2019-11-15',
'2019-12-20', '2020-01-17', '2020-02-21', '2020-03-20',
'2020-04-17', '2020-05-15', '2020-06-19', '2020-07-17',
'2020-08-21'],
dtype='datetime64[ns]', freq='WOM-3FRI')
You can use standard python functions to find the third friday of this month:
from datetime import timedelta, date
import calendar
def next_third_friday(d):
""" Given a third friday find next third friday"""
d += timedelta(weeks=4)
return d if d.day >= 15 else d + timedelta(weeks=1)
def third_fridays(d, n):
"""Given a date, calculates n next third fridays"""
# Find closest friday to 15th of month
s = date(d.year, d.month, 15)
result = [s + timedelta(days=(calendar.FRIDAY - s.weekday()) % 7)]
# This month's third friday passed. Find next.
if result[0] < d:
result[0] = next_third_friday(result[0])
for i in range(n - 1):
result.append(next_third_friday(result[-1]))
return result
We can apply the above function to get the timestamps of the next fridays:
import time
def timestamp(d):
return int(time.mktime(d.timetuple()))
fridays = third_fridays(date.today(), 2)
print(fridays)
print(map(timestamp, fridays))
Output:
[datetime.date(2015, 3, 20), datetime.date(2015, 4, 17)]
[1426802400, 1429218000]
How about a more straightforward answer:
import calendar
c = calendar.Calendar(firstweekday=calendar.SATURDAY)
monthcal = c.monthdatescalendar(my_year, my_month)
monthly_expire_date = monthcal[2][-1]
I generalized #pourhaus answer to find the nth day of any month:
def nth_day_of_month(month, year, day_of_week, n):
first_possible_day = {1: 1, 2: 8, 3: 15, 4: 22, 5: 29}[n]
d = datetime.date(year, month, first_possible_day)
w = d.weekday()
if w != day_of_week:
d = d.replace(day=(first_possible_day + (day_of_week - w) % 7))
return d
its easy to use dateutil to get the next friday
import dateutil.parser as dparse
from datetime import timedelta
next_friday = dparse.parse("Friday")
one_week = timedelta(days=7)
friday_after_next = next_friday + one_week
last_friday = friday_after_next + one_week
this leverages the fact that there is always a week between fridays ... although Im not sure this answers your question it should at the very least provide you with a good starting point
Using dateutil.relativedelta:
from dateutil.relativedelta import relativedelta, FR # $ pip install python-dateutil
def third_friday_dateutil(now):
"""the 3rd Friday of the month, not the 3rd Friday after today."""
now = now.replace(day=1) # 1st day of the month
now += relativedelta(weeks=2, weekday=FR)
return now
Or using dateutil.rrule:
from datetime import date, timedelta
from dateutil.rrule import rrule, MONTHLY, FR
def third_friday_rrule(now):
return rrule(MONTHLY, count=1, byweekday=FR, bysetpos=3, dtstart=now.replace(day=1))[0]
def get_third_fris_rrule(how_many):
return list(rrule(MONTHLY, count=how_many, byweekday=FR, bysetpos=3, dtstart=date.today()+timedelta(1)))
Here's a brute force solution (15x times faster):
#!/usr/bin/env python
import calendar
from datetime import date, timedelta
from itertools import islice
DAY = timedelta(1)
WEEK = 7*DAY
def fridays(now):
while True:
if now.weekday() == calendar.FRIDAY:
while True:
yield now
now += WEEK
now += DAY
def next_month(now):
"""Return the first date that is in the next month."""
return (now.replace(day=15) + 20*DAY).replace(day=1)
def third_friday_brute_force(now):
"""the 3rd Friday of the month, not the 3rd Friday after today."""
return next(islice(fridays(now.replace(day=1)), 2, 3))
def get_third_fris(how_many):
result = []
now = date.today()
while len(result) < how_many:
fr = third_friday_brute_force(now)
if fr > now: # use only the 3rd Friday after today
result.append(fr)
now = next_month(now)
return result
print(get_third_fris(6))
Output
[datetime.date(2015, 3, 20),
datetime.date(2015, 4, 17),
datetime.date(2015, 5, 15),
datetime.date(2015, 6, 19),
datetime.date(2015, 7, 17),
datetime.date(2015, 8, 21)]
See Converting datetime.date to UTC timestamp in Python
Here's comparison with other solutions and tests (for all possible 400 years patterns).
I generalized my answer so that anyone can use it for any Nth weekday of a month and using minimal default libraries. My use was to find the DST (daylight savings time) dates for the year (2nd sunday in March & 1st sunday in November).
# Libraries:
from datetime import datetime
# Function:
def get_nth_day_of_month(year, month, Nth, weekday):
# Process is to find out what weekday the 1st of the month is
# And then go straight to the desired date by calculating it
first_of_month_weekday = datetime(year, month, 1).weekday()
day_desired = 7 * (Nth-1) + (weekday - first_of_month_weekday)
if day_desired < 1 : day_desired += 7 #correction for some 1st-weekday situations
return datetime(year, month, day_desired)
# Config:
year = 2022
month = 3 #DST starts in March
weekday = 6 #sunday
Nth = 2 #2nd sunday
dst_start = get_nth_day_of_month(year, month, Nth, weekday)
For my case, this generates the start of DST this year:
In [2]: dst_start
Out [2]: datetime.datetime(2022, 3, 13, 0, 0)
Then for the end of DST in 2022:
month = 11
Nth = 1
dst_end = get_nth_day_of_month(year, month, Nth, weekday)
The result is:
In[4]: dst_end
Out[4]: datetime.datetime(2022, 11, 5, 0, 0)
So in 2022, DST runs from 2022-03-13 to 2022-11-05.
Standard:
Days are numbered Monday = 0 to Sunday = 6
Pure python with no external libs.
Returns the expected day-of-month.
Note: Based on answer from #autonopy, but works.
from datetime import datetime
def get_nth_day_of_month(year, month, Nth, weekday):
first_of_month_weekday = datetime(year, month, 1).weekday()
# Find weekday offset from beginning of month
day_offset = (weekday - first_of_month_weekday) + 1
if day_offset < 1:
day_offset += 7 # correction for some 1st-weekday situations
# Add N weeks
return 7 * (Nth - 1) + day_offset
Tests:
>>> # first Monday of Nov 2021
>>> get_nth_day_of_month(2021, 11, 1, 0)
1
>>> # first Monday of January 2022
>>> get_nth_day_of_month(2022, 1, 1, 0)
3
>>> # first Monday of May 2022
>>> get_nth_day_of_month(2022, 5, 1, 0)
2
>>> # Mother's day 2022
>>> get_nth_day_of_month(2022, 5, 2, 0)
9
Assuming you use pandas:
def exp_friday(df):
mask = np.where((df.index.day > 14) &
(df.index.day < 22) &
(df.index.dayofweek == 4), True, False)
return df[mask]
This is a generic function to give you all the dates of a specific week in a list form.
def frecuencia_daymng(self, start_day, year, month, dayofweek):
"""dayofweek starts on MONDAY in 0 index"""
c = calendar.Calendar(firstweekday=start_day)
monthcal = c.monthdatescalendar(year, month)
ldates = []
for tdate in monthcal:
if tdate[dayofweek].month == month:
ldates.append(tdate[dayofweek])
return ldates
Lets say you want all the mondays of the 2020 10.
frecuencia_daymng(calendar.MONDAY, 2020, 10, 0)
This will give you the output.
[datetime.date(2020, 10, 5),
datetime.date(2020, 10, 12),
datetime.date(2020, 10, 19),
datetime.date(2020, 10, 26)]
So now you have the first, second ... etc monday of the month.
My suggestion is to start with the first day of the month, then find the closest Friday.
4 is represented as Friday from the datetime.weekday() method.
So we then subtract the weekday of the first of the month from 4(Friday)
If the result is negative the closest Friday found was the previous month, so we add 7 days, otherwise we already have the first Friday.
Then the result is as simple as adding another 14 days to get the third Friday and then add the timedelta representing the third Friday to the first day of the month.
from datetime import datetime, timedelta
def get_third_friday(year, month):
first_day_of_month = datetime(year, month, 1)
closest_friday = 4 - first_day_of_month.weekday()
if closest_friday < 0:
first_friday = closest_friday + 7
else:
first_friday = closest_friday
third_friday = first_friday + 14
return first_day_of_month + timedelta(third_friday)
Here's a solution where someone has figured it out already: the relativedelta module that's an extension from the Python dateutil package (pip install python-dateutil).
import datetime
from dateutil import relativedelta
def third_fridays(n):
first_of_this_month = datetime.date.today().replace(day=1)
return (
first_of_this_month
+ relativedelta.relativedelta(weekday=relativedelta.FR(3), months=i)
for i in range(n)
)
The key part here of course is the weekday=relativedelta.FR(3) which says exactly what's needed: the third Friday of the month. Here are the relevant part of the docs for the weekday parameter,
weekday:
One of the weekday instances (MO, TU, etc) available in the
relativedelta module. These instances may receive a parameter N,
specifying the Nth weekday, which could be positive or negative
(like MO(+1) or MO(-2)).
(For those new to Python return (...) is a generator expression which you can just treat as something to iterate over, e.g., for friday in third_fridays(18): print(friday))
from dateutil.relativedelta import *
from datetime import *
def find_mth_friday(your_date,m):
mth_friday = your_date + relativedelta(day=1, weekday=FR(m)) #sets day=1 in your_date and adds m fridays to it.
mth_friday_timestamp = int(mth_friday.strftime("%s")) #converting datetime to unix timestamp
return mth_friday_timestamp
def get_third_fris(n):
output_timestamps = []
today = datetime.now() #gets current system date
for i in range(1,n+1): #value of i varies from 1 to 6 if n=6
next_month = today + relativedelta(months=+i) #adds i months to current system date
third_friday = find_mth_friday(next_month,3) #finds third friday of the month using 'find_mth_friday()', the function we defined
output_timestamps.append(third_friday)
return output_timestamps
print(get_third_fris(6)) #let's try invoking our function with n=6 dates
This is what you wanted right?

Count number of sundays in current month

How can I get the numberof Sundays of the current month in Python?
Anyone got any idea about this?
This gives you the number of sundays in a current month as you wanted:
import calendar
from datetime import datetime
In [367]: len([1 for i in calendar.monthcalendar(datetime.now().year,
datetime.now().month) if i[6] != 0])
Out[367]: 4
I happened to need a solution for this, but was unsatisfactory with the solutions here, so I came up with my own:
import calendar
year = 2016
month = 3
day_to_count = calendar.SUNDAY
matrix = calendar.monthcalendar(year,month)
num_days = sum(1 for x in matrix if x[day_to_count] != 0)
I'd do it like this:
import datetime
today = datetime.date.today()
day = datetime.date(today.year, today.month, 1)
single_day = datetime.timedelta(days=1)
sundays = 0
while day.month == today.month:
if day.weekday() == 6:
sundays += 1
day += single_day
print 'Sundays:', sundays
My take: (saves having to worry about being in the right month etc...)
from calendar import weekday, monthrange, SUNDAY
y, m = 2012, 10
days = [weekday(y, m, d+1) for d in range(*monthrange(y, m))]
print days.count(SUNDAY)
Or, as #mgilson has pointed out, you can do away with the list-comp, and wrap it all up as a generator:
sum(1 for d in range(*monthrange(y,m)) if weekday(y,m,d+1)==SUNDAY)
And I suppose, you could throw in a:
from collections import Counter
days = Counter(weekday(y, m, d + 1) for d in range(*monthrange(y, m)))
print days[SUNDAY]
Another example using calendar and datetime:
import datetime
import calendar
today = datetime.date.today()
m = today.month
y = today.year
sum(1 for week in calendar.monthcalendar(y,m) if week[-1])
Perhaps a slightly faster way to do it would be:
first_day,month_len = monthrange(y,m)
date_of_first_sun = 1+6-first_day
print sum(1 for x in range(date_of_first_sun,month_len+1,7))
You can do this using ISO week numbers:
from datetime import date
bom = date.today().replace(day=1) # first day of current month
eom = (date(bom.year, 12, 31) if bom.month == 12 else
(bom.replace(month=bom.month + 1) - 1)) # last day of current month
_, b_week, _ = bom.isocalendar()
_, e_week, e_weekday = eom.isocalendar()
num_sundays = (e_week - b_week) + (1 if e_weekday == 7 else 0)
In general for a particular day of the week (1 = Monday, 7 = Sunday) the calculation is:
num_days = ((e_week - b_week) +
(-1 if b_weekday > day else 0) +
( 1 if e_weekday >= day else 0))
import calendar
MONTH = 10
sundays = 0
cal = calendar.Calendar()
for day in cal.itermonthdates(2012, MONTH):
if day.weekday() == 6 and day.month == MONTH:
sundays += 1
PAY ATTENTION:
Here are the Calendar.itermonthdates's docs:
Return an iterator for one month. The iterator will yield datetime.date
values and will always iterate through complete weeks, so it will yield
dates outside the specified month.
That's why day.month == MONTH is needed
If you want the weekdays to be in range 0-6, use day.weekday(),
if you want them to be in range 1-7, use day.isoweekday()
My solution.
The following was inspired by #Lingson's answer, but I think it does lesser loops.
import calendar
def get_number_of_weekdays(year: int, month: int) -> list:
main_calendar = calendar.monthcalendar(year, month)
number_of_weeks = len(main_calendar)
number_of_weekdays = []
for i in range(7):
number_of_weekday = number_of_weeks
if main_calendar[0][i] == 0:
number_of_weekday -= 1
if main_calendar[-1][i] == 0:
number_of_weekday -= 1
number_of_weekdays.append(number_of_weekday)
return sum(number_of_weekdays) # In my application I needed the number of each weekday, so you could return just the list to do that.

Categories