Получите день от свидания в пандах

Опубликовано: 27 Марта, 2022

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.

Примеры :

Мы будем использовать формат даты "дд / мм / гггг"

Ввод: '24.07.2020' 
Выход: 'Пятница' 

Ввод: 01/01/2001.
Выход: «Понедельник» 

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.

# 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 DataTime
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())

Выход :

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 .

# 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())

Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.