Home > Net >  trouble calculating the amount of Sundays inbetween 2 dates
trouble calculating the amount of Sundays inbetween 2 dates

Time:09-22

I was asked to create a program that calculates the number of Sundays inbetween 2 dates! I have been searching numerous articles and documentation but I still have a hard time understanding syntax. (2 months into my coding course with 0 technology and computer experience.)

I am having trouble understanding the logic of how to associate the calendar with the days inside the Dictionary. My current code is as follows :

def difference_between_days():
    daysDict = {0 : "Monday",1: "Tuesday",2: "Wedensday",3: "Thursday",4: "Friday",5: 
"Saturday",6: "Sunday"}

    first_date = date(2021,7,28)
    end_date = date(2022,7,28)

    difference_between_dates = end_date - first_date
    print(f"There are {difference_between_dates.days} days inbetween the two dates!")

    d = date.weekday(first_date)
    dd = daysDict[d]
    print(f"The first date selected is a : {dd}")


difference_between_days()

edit: When using certain functions such as .isoweekday I run into problems printing because it returns me something like this "<built-in method isoweekday of datetime.date object at 0x000001EB956FA0F0>" and I still have not reached classes yet!

CodePudding user response:

Python is not my weapon of choice, but this should do the job. The idea is to use weekday() to move the start date to the following sunday, and the endate to the previous sunday. Then count the days in between, divide by 7 (weeks) and add 1 because both ends are Sundays.

Don't hesitate to ask if it's not clear, and accept the answer if it it.

HTH

from datetime import datetime, timedelta 

def number_of_sundays(from_str, to_str):
    
    # get date objects from the string representations in Ymd format
    from_date = datetime.strptime(from_str, "%Y/%m/%d")
    to_date = datetime.strptime(to_str, "%Y/%m/%d")

    # move start date to the following sunday
    from_date = from_date   timedelta(days=6-from_date.weekday())
    # move end date to the previous sunday
    to_date = to_date   timedelta(days=-to_date.weekday()-1)

    # now both dates are sundays so the number is the number of weeks   1
    nb_sundays = 1   (to_date - from_date).days / 7   
    return nb_sundays 

print(number_of_sundays("2022/08/28", "2022/09/20"))

CodePudding user response:

I would like to inform that Wolf D's response answered and worked efficenctly and accuratley as i needed! Thank you Wolf!

  • Related