Skip to content
Advertisement

How to find the most common day name in a month?

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.

import calendar

def usingcalendar(datetuple):
    l = []
    dt=list(datetuple)
    obj = calendar.Calendar()
    for day in obj.itermonthdates(dt[0], dt[1]):
        l.append(day)
    rev = l[:-8:-1]
    rev.reverse()
    print(rev)

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

[datetime.date(2020, 2, 24), datetime.date(2020, 2, 25), datetime.date(2020, 2, 26), 
 datetime.date(2020, 2, 27), datetime.date(2020, 2, 28), datetime.date(2020, 2, 29), 
 datetime.date(2020, 3, 1)]

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.

import calendar
from collections import Counter

cal = calendar.Calendar()
year = 2020
month = 1
count = Counter(d.strftime('%A') for d in cal.itermonthdates(year, month) if d.month==month)

Then for example

>>> count
Counter({'Wednesday': 5, 'Thursday': 5, 'Friday': 5, 'Saturday': 4, 'Sunday': 4, 'Monday': 4, 'Tuesday': 4})
>>> count.most_common(1)
[('Wednesday', 5)]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement