Open In App

Get the day from a date in Pandas

Last Updated : 09 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a particular date, it is possible to obtain the day of the week on which the date falls. This is achieved with the help of Pandas library and the to_datetime() method present in pandas. 
In most of the datasets the Date column appears to be of the data type String, which definitely isn’t comfortable to perform any calculations with that column, such as the difference in months between 2 dates, the difference in time or finding the day of the week. Hence Pandas provides a method called to_datetime() to convert strings into Timestamp objects.
Examples : 
 

We'll use the date format 'dd/mm/yyyy'

Input :  '24/07/2020' 
Output : 'Friday' 

Input : '01/01/2001'
Output : 'Monday' 

Once we convert a date in string format into a date time object, it is easy to get the day of the week using the method day_name() on the Timestamp object created.
Example 1 : In this example, we pass a random date with the type ‘str’ and format ‘dd/mm/yyyy’ to the to_datetime() method . As a result we get a Timestamp pandas object. Then we retrieve the day of the week by the Timestamp class’s day_name() method.
 

Python3




# importing the module
import pandas as pd
 
# the date in "dd/mm/yyyy" format
date = "19/02/2022"
print("Initially the type is : ", type(date))
 
# converting string to DateTime
date = pd.to_datetime(date, format = "%d/%m/%Y")
print("After conversion, the type is : ", type(date))
 
# fetching the day
print("The day is : " + date.day_name())


Output : 
 

Example 2 : In the below example, dates of different formats have been converted to a Timestamp object and then their respective days of the week are retrieved using day_name() method . 
 

Python3




# importing the module
import pandas as pd
 
# 'dd-mm-yyyy'
date_1 = '22-07-2011' 
date_1 = pd.to_datetime(date_1, format ="%d-%m-%Y")
 
print("The day on the date " + str(date_1) +
      " is : " + date_1.day_name())
 
# 'mm.dd.yyyy'
date_2 = '12.03.2000' 
date_2 = pd.to_datetime(date_2, format ="%m.%d.%Y")
print("The day on the date " + str(date_2) +
      " is : " + date_2.day_name())
 
# 'yyyy / dd / mm'
date_3 = '2004/9/4'   
date_3 = pd.to_datetime(date_3, format ="%Y/%d/%m")
print("The day on the date " + str(date_2) +
      " is : " + date_3.day_name())


Output : 
 

 



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: