I have a daterange and I need to know how many Sunday there is between the two dates. Is there a better way than looping on all the days and check if it's Sunday ?
from datetime import datetime
first_date = '2021-01-01'
final_date = '2021-01-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
CodePudding user response:
Loop through the dates using a while loop, at the end of it add one day to the first date. To get the day of the week use the weekday
method.
from datetime import datetime, timedelta
first_date = "2021-01-01"
final_date = "2021-01-31"
first_date = datetime.strptime(first_date, "%Y-%m-%d")
last_date = datetime.strptime(final_date, "%Y-%m-%d")
delta = timedelta(days=1) # looping interval
sundays = 0
while first_date <= last_date: # or use `<` if you don't want it inclusive
if first_date.weekday() == 6:
sundays = 1
first_date = delta
print(sundays)
CodePudding user response:
You just need to find the last and first Sunday in the range and then find number of weeks between them. Example below
from datetime import datetime, timedelta
first_date = '2021-01-01'
final_date = '2021-01-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
# Identify the fist sunday from start date
first_sunday = first_date timedelta(days=6 - first_date.weekday())
# Identify the last sunday from end date
last_sunday = last_date - timedelta(days=6 - last_date.weekday())
# Get the gap between the two dates and find the number of weeks
total_sundays = (last_sunday - first_sunday).days // 7 1
print(total_sundays)
gives output
5
This is a solution, that includes the start and end date. If you want to avoid inclusive, adjust the count accordingly.
CodePudding user response:
I mean as you know that the week usually doesn't skip days you can just compare the start and end date get the number of days in that range and then divide it by 7 (integer division //) then you've already got the full weeks aka the number of sundays, so all you need now is check the left over days for sundays.
from datetime import datetime, timedelta
first_date = "2021-01-01"
final_date = "2021-01-31"
first_date = datetime.strptime(first_date, "%Y-%m-%d")
last_date = datetime.strptime(final_date, "%Y-%m-%d")
days = (last_date-first_date).days
num_sun = days//7
if (days % 7 first_date.isoweekday()) >= 7:
num_sun =1
Apparently isoweekdays are numbered from monday = 1 to sunday =7. So start_day left_overdays from the week numbering should be smaller than 7 if I didn't mess up my calculation somewhere.