Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of sundays in current month

Tags:

python

How can I get the numberof Sundays of the current month in Python?

Anyone got any idea about this?

like image 341
Alchemist777 Avatar asked Oct 19 '12 11:10

Alchemist777


3 Answers

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
like image 50
root Avatar answered Oct 21 '22 17:10

root


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)
like image 31
Lingson Avatar answered Oct 21 '22 17:10

Lingson


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
like image 30
jro Avatar answered Oct 21 '22 16:10

jro