Handling Dates in Any Year

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to create a Python script that prints all the Sundays in a given year. This is a useful skill for anyone who needs to work with dates and time-related tasks in their programming projects.

👀 Preview

python Sunday.py 2022
2022-01-02
2022-01-09
2022-01-16
2022-01-23
2022-01-30
2022-02-06
2022-02-13
2022-02-20
...

🎯 Tasks

In this project, you will learn:

  • How to use the datetime and calendar modules in Python to handle dates
  • How to write a function that calculates and returns a list of all the Sundays in a given year
  • How to handle user input and command-line arguments in a Python script
  • How to enhance and customize the script to make it more flexible and user-friendly

🏆 Achievements

After completing this project, you will be able to:

  • Understand how to work with dates and time in Python
  • Write a script that can print all the Sundays in a given year
  • Customize the script to handle different years and user input
  • Apply your newfound knowledge to other date-related tasks in your programming projects

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/while_loops("`While Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/AdvancedTopicsGroup -.-> python/iterators("`Iterators`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/with_statement -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/variables_data_types -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/numeric_types -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/type_conversion -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/conditional_statements -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/for_loops -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/while_loops -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/lists -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/tuples -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/function_definition -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/importing_modules -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/standard_libraries -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/iterators -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/date_time -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/data_collections -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/os_system -.-> lab-302733{{"`Handling Dates in Any Year`"}} python/build_in_functions -.-> lab-302733{{"`Handling Dates in Any Year`"}} end

Create the Sunday.py File

In this step, you will create the Sunday.py file and set up the initial structure of the script.

  1. Create a Sunday.py file in the ~/project directory.
cd ~/project
touch Sunday.py
  1. Add the following code to the file:
import datetime
import sys


## Function to print all the Sundays in a given year
def print_sundays(year):
    sundays = []  ## List to store the Sundays
    date = datetime.date(year, 1, 1)  ## Start with January 1st of the given year
    delta = datetime.timedelta(days=1)  ## Define a timedelta of 1 day

    ## Find the first Sunday of the year
    while date.weekday() != 6:  ## 6 represents Sunday (Monday is 0 and Sunday is 6)
        date += delta  ## Move to the next day

    ## Print all the Sundays in the year
    while date.year == year:  ## Loop until the year changes
        sundays.append(
            date.strftime("%Y-%m-%d")
        )  ## Add the Sunday to the list (formatted as YYYY-MM-DD)
        date += datetime.timedelta(
            weeks=1
        )  ## Move to the next Sunday (increment by 1 week)

    return sundays  ## Return the list of Sundays


## Read the year from the command line argument
if len(sys.argv) > 1:
    year = int(sys.argv[1])  ## Convert the command-line argument to an integer
    sundays = print_sundays(year)  ## Call the function to get the list of Sundays
    for sunday in sundays:
        print(sunday)  ## Print each Sunday
else:
    print(
        "Please provide a year as a command-line argument."
    )  ## Display an error message if no year is provided

This code sets up the basic structure of the Sunday.py script, including the print_sundays() function and the command-line argument handling.

Understand the Code

In this step, you will understand the purpose and functionality of the code in the Sunday.py file.

  1. The print_sundays() function takes a year parameter and returns a list of all the Sundays in that year.
  2. The function starts by creating a datetime.date object with the given year and the first day of the year (January 1st).
  3. It then finds the first Sunday of the year by iterating through the days until the weekday is 6 (Sunday).
  4. Once the first Sunday is found, the function enters a loop that continues until the end of the year. In each iteration, it adds the current Sunday to the sundays list and moves to the next Sunday (by adding a timedelta of 1 week).
  5. Finally, the function returns the list of Sundays.
  6. The main part of the script reads the year from the command-line argument and calls the print_sundays() function with the provided year. It then prints each Sunday in the list.
  7. If no command-line argument is provided, the script displays an error message.

Run the Script

In this step, you will run the Sunday.py script and observe the output.

  1. Open a terminal and navigate to the /home/labex/project directory.
  2. Run the Sunday.py script with a specific year as a command-line argument:
python Sunday.py 2022

You should see the following output:

2022-01-02
2022-01-09
2022-01-16
2022-01-23
2022-01-30
2022-02-06
2022-02-13
2022-02-20
2022-02-27
2022-03-06
2022-03-13
2022-03-20
2022-03-27
2022-04-03
2022-04-10
2022-04-17
2022-04-24
2022-05-01
2022-05-08
2022-05-15
2022-05-22
2022-05-29
2022-06-05
2022-06-12
2022-06-19
2022-06-26
2022-07-03
2022-07-10
2022-07-17
2022-07-24
2022-07-31
2022-08-07
2022-08-14
2022-08-21
2022-08-28
2022-09-04
2022-09-11
2022-09-18
2022-09-25
2022-10-02
2022-10-09
2022-10-16
2022-10-23
2022-10-30
2022-11-06
2022-11-13
2022-11-20
2022-11-27
2022-12-04
2022-12-11
2022-12-18
2022-12-25

The output shows all the Sundays in the year 2022.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like