Find the day of week with a given date in Python
Ever tried to find the day in a week using a date given in Python?
It is a tedious task to do on the paper. Hence I come up with a program to do this job. In this tutorial, we will learn about How to find the day of a week using a date given in Python.
And also look some examples to understand the code.
datetime module to find the day of a week in Python
The program for this tutorial is given below. Keep reading to find insides of this program.
import datetime week_days= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday'] l=list(map(int, input("Enter date \n eg: 05/05/2019 \n\n").split('/'))) day=datetime.date(l,l,l).weekday() print(week_days[day])
Let us look at the program.
First of all import the datetime module
week_days= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday']
is the list of weekdays.
The input statement in third line takes the input ( eg: 05/05/2019)
input("Enter date \n eg: 05/05/2019 \n\n").split('/')
It gives the output of a list with date, month, year in string format ( [‘date’, ‘month’ , ‘year’])
The function datetime.date() in the statement
datetime.date(year, month, date)
takes the integer values in place of year, month and date, since we are using these values from the list ‘l’, it must contain integers.
The function map() converts the list of strings to the list of integers.
gives an integer(0-6) as the output.
The variable ‘day’ stores this value.
This value is related to the day of a week as follows.
Monday = 0
Tuesday = 1
Wednesday = 2
Thursday = 3
Friday = 4
Saturday = 5
Sunday = 6
Therefore, the statement
prints the corresponding day w.r.t value stored in the variable ‘day’.
Input = 14/06/2019
l = [14, 6, 2019] day=4
Similar programs using datetime module are