Python program to find the first day of given year
Given a year as input, write a Python to find the starting day of the given year. We will use the Python datetime library in order to solve this problem.
Example:
Input : 2010 Output :Friday
Input :2019 Output :Tuesday
Below is the implementation:
Python3
# Python program to find the first day of given year # import datetime library import datetime def Startingday(year): Days = [ "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday" ] # Creating an object for 1st January of that particular year # For that we are passing three argument (1) year (2) month # i.e 1 for january (3) date i.e 1 for starting day of # that particular year a = datetime.datetime(year, 1 , 1 ).weekday() # f-String is used for printing Startingday of a particular year print (f "Starting day of {year} is {Days[a]}." ) # Driver Code year = 2010 Startingday(year) |
Output
Starting day of 2010 is Friday.
Time Complexity: O(1)
Space Complexity: O(1)
Alternate Approach Using the calendar library
step by step approach
- Import the calendar library.
- Define a function Startingday(year) that takes a single argument year.
- Create a list called Days that contains the names of the days of the week in order, starting with
- Monday and ending with Sunday.
- Call the calendar.weekday(year, 1, 1) function, passing in the year argument and the values 1 and 1 for the month and day arguments. This function returns an integer representing the day of the week for the given date, where Monday is 0 and Sunday is 6.
- Use the integer returned by calendar.weekday() to index into the Days list and get the name of the starting day of the year.
- Print a message that includes the year argument and the name of the starting day of the year.
- Define a variable year with the value 2019.
- Call the Startingday(year) function, passing in the year argument.
- The program outputs a message indicating the starting day of the year 2019, which is a Tuesday.
- The author of the code is credited in a comment at the end of the program.
Python3
# Using the calendar library import calendar def Startingday(year): Days = [ "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" , "Sunday" ] day = calendar.weekday(year, 1 , 1 ) print (f "Starting day of {year} is {Days[day]}." ) #Driver Code year = 2019 Startingday(year) #This code is contributed by Edula Vinay Kumar Reddy |
Output
Starting day of 2019 is Tuesday.
Time Complexity: O(1)
Auxiliary Space: O(1)