Python: Select all the Sundays of a specified year
Python Datetime: Exercise-15 with Solution
Write a Python program to select all the Sundays in a specified year.
Sample Solution:
Python Code:
# Import the date class and the timedelta class from the datetime module
from datetime import date, timedelta
# Define a function named all_sundays that takes a year as input
def all_sundays(year):
# Set dt to January 1st of the given year
dt = date(year, 1, 1)
# Move dt to the first Sunday of the given year
dt += timedelta(days=6 - dt.weekday())
# Iterate through all Sundays of the given year
while dt.year == year:
# Yield the current date (dt) as a result
yield dt
# Move to the next Sunday by adding 7 days
dt += timedelta(days=7)
# Iterate through all Sundays of the year 2020 using the all_sundays function
for s in all_sundays(2020):
# Print each Sunday
print(s)
Output:
2020-01-05 2020-01-12 2020-01-19 2020-01-26 2020-02-02 ----- 2020-12-06 2020-12-13 2020-12-20 2020-12-27
Explanation:
In the exercise above,
- The code imports the "date" class and the "timedelta" class from the "datetime" module.
- Define the function to find Sundays:
- The code defines a function named "all_sundays()" that takes a 'year' as input.
- Find the first Sunday of the year:
- It initializes a date 'dt' to January 1st of the given year (date(year, 1, 1)).
- It adjusts 'dt' to the first Sunday of the given year by adding a 'timedelta' representing the difference between the weekday of January 1st and Sunday (6 - dt.weekday()).
- Generating all Sundays of the year:
- It iterates through all Sundays of the given year using a while loop.
- In each iteration, it yields the current date 'dt'.
- Then, it moves 'dt' to the next Sunday by adding 7 days (dt += timedelta(days=7)).
- Printing all Sundays of the year 2020:
- It iterates through all Sundays of the year 2020 using a for loop with the "all_sundays(2020)" function call.
- In each iteration, it prints the Sunday date.
Flowchart:
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to find the date of the first Monday of a given week.
Next: Write a program to add year(s) with a given date and display the new date.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/date-time-exercise/python-date-time-exercise-15.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics