Home » Python » Python programs

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?
Submitted by Bipin Kumar, on November 13, 2019

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. To this, we will use the calendar module which provides us various functions to solve the problem related to date, month and year. 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 to solve this problem:

  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.
    1. If the date is valid then execute the next statement.
    2. If date is invalid then show ‘you have entered an invalid date' to the user.
  4. Print the weekday of the given date.

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

Code:

# 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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.