Find the day of the week for a given date in the past or future in Python

Here, we will learn how to find the day of the week for a given particular date in the past or future in the Python programming language? By Bipin Kumar Last updated : January 05, 2024

Problem statement

In this problem, a particular date will be provided by the user which may be from the past or future and we have to find the weekday.

Finding the day of the week for a given date in the past or future

To this, we will use the calendar module which provides us various functions to solve the problem related to date, month and year. You can use the calendar.weekday() method to get the number of the day of the week and then get the weekday name from the list of the weekday names. Before going to find the weekday of a given particular date, we have to check whether the given date is valid or not. If the given date is not valid then we will get some error. So, to overcome this type of error we will use the try-except statement.

Syntax of try-except statement:

try:
    #statement 

except error_types:
    #statement

Algorithm

The algorithm to find the day of the week for a given date in the past or future is:

  1. Import calendar module in the program.
  2. Take a date from the user in the form of date(d) - month(m) -year(y).
  3. Check the given date is valid or not.
  4. If the date is valid then execute the next statement.
  5. If date is invalid then show "you have entered an invalid date" to the user.
  6. Print the weekday of the given date.

Let's start writing the Python program by the implementation of the above algorithm.

Python code to find the day of the week for a given date in the past or future

# importing the module
import calendar

d, m, y = map(int, input("Enter the value of date,month and year: ").split())

a = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

try:
    s = calendar.weekday(y, m, d)
    print("Weekday:", a[s])
except ValueError:
    print("You have entered an invalid date.")

Output

The output of the above code is:

RUN 1:
Enter the value of date, month and year: 28 10 2019
Weekday: Monday

RUN 2:
Enter the value of date, month and year: 32 10 2019
You have entered an invalid date.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.