zhengheng lin
zhengheng lin

Reputation: 35

Python - count the number of sundays on the first day of month between two dates

I need to calculate the number of sundays by importing calendar, but I don't have a clue on how to determine if those sundays are on the first day of the month. Any guide please?

Upvotes: 0

Views: 2358

Answers (1)

Eugene Sh.
Eugene Sh.

Reputation: 18371

Use the standard datetime module. Here is a very simple naive algorithm to approach your problem:
1) Get the starting and ending dates to look between them
2) Iterate on all dates between the given two (using the date's ordinal)
3) Check whether or not it is Sunday first usind date.day and date.weekday

from datetime import  date

date1 = date(2005, 1, 1)
date2 = date(2008, 1, 1)

date1_ord = date1.toordinal()
date2_ord = date2.toordinal()
cnt = 0

for d_ord in range(date1_ord, date2_ord):
    d = date.fromordinal(d_ord)
    if (d.weekday() == 6) and (d.day == 1):
        cnt = cnt + 1

print("Number of Sunday 1'st days is {}".format(cnt))

Upvotes: 1

Related Questions