Is there a way to print the day of the week which appears most frequent in the specified month and year as a string. Like Monday
and Tuesday
and if there are any multiple days, the first one should be displayed.
First I tried to check with the datetime
output but unable to find the calendar module to get this as day output.
JavaScript
x
12
12
1
import calendar
2
3
def usingcalendar(datetuple):
4
l = []
5
dt=list(datetuple)
6
obj = calendar.Calendar()
7
for day in obj.itermonthdates(dt[0], dt[1]):
8
l.append(day)
9
rev = l[:-8:-1]
10
rev.reverse()
11
print(rev)
12
I was trying to use calendar.itermonthdays
to get the required iterator to use that to display days like ‘Monday’, Tuesday’. But only came up to this
JavaScript
1
4
1
[datetime.date(2020, 2, 24), datetime.date(2020, 2, 25), datetime.date(2020, 2, 26),
2
datetime.date(2020, 2, 27), datetime.date(2020, 2, 28), datetime.date(2020, 2, 29),
3
datetime.date(2020, 3, 1)]
4
Advertisement
Answer
You can use collections.Counter
for this. You can call the calendar’s itermonthdates
for a given year and month, then create a Counter
of the weekday names using the '%A'
format specifier of datetime
.
JavaScript
1
8
1
import calendar
2
from collections import Counter
3
4
cal = calendar.Calendar()
5
year = 2020
6
month = 1
7
count = Counter(d.strftime('%A') for d in cal.itermonthdates(year, month) if d.month==month)
8
Then for example
JavaScript
1
5
1
>>> count
2
Counter({'Wednesday': 5, 'Thursday': 5, 'Friday': 5, 'Saturday': 4, 'Sunday': 4, 'Monday': 4, 'Tuesday': 4})
3
>>> count.most_common(1)
4
[('Wednesday', 5)]
5