How to find day name from date in Python?

This tutorial will show you how to find the day name from the given date in Python. We can use strptime() or strftime() function to do this task.

Below are two methods to get day name from date:

Method 1: Using strptime() function

Let us see the following example.

import datetime 
date=str(input('Enter the date(for example:09 02 2019):'))
day_name= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday']
day = datetime.datetime.strptime(date, '%d %m %Y').weekday()
print(day_name[day]) 
  

In this example, we have imported datetime module that is available in Python.

Let us look at the working of this program.

  • First, the date is given as a string input.
  • Define a list with the name of the days of a week named day_name.
  • Then strptime() function formats the input string to a DD:MM:YYYY format.
  • weekday() function returns an integer corresponding to the day of a week
  • Finally, print the day of the date by specifying that returned integer as an index value of a list day_name.

Input:

Enter the date(for example:09 02 2019):09 12 2019

Output:

Monday

Method 2: Using strftime() function

Let us look at the following example.

import datetime  
from datetime import date 
date=str(input('Enter the date(for example:09 02 2019):'))
day, month, year = date.split(' ')     
day_name = datetime.date(int(year), int(month), int(day)) 
print(day_name.strftime("%A")) 

In this example also, the date is taken as string input. The input string is separated into a day, month and year using split() function. The strftime() function takes one or two format codes and returns a formatted string. The directive “%A” is passed to provide a full weekday name for the given date.

Input:

Enter the date(for example:09 02 2019):09 12 2019

Output:

Monday

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *