Python - How to convert Datetime to Year, Month, Day using pandas


Let's flair it the Python way:

Sometimes there is a requirement to just get the year,month or day from a datetime type column to create more granular visuals or summarize the data on basis of year, month or day.

In python, Pandas library can be used to achieve this.

You can use to_datetime() and strftime() functions to achieve this.

 

Steps Involved :

1) Convert string datetime column to datetime dtype.

import pandas as pd 

df['datetime_col'] = pd.to_datetime(df['datetime_col'])


2) use strftime() function from the datetime.datetime class.

import datetime

df['month'] = df['datetime_col'].map(lambda x: x.strftime('%B')) 

df['day'] = df['datetime_col'].map(lambda x: x.strftime('%A'))

3) Some of the parameter list to get year, month, day in different format : 

%a - sun

%A - sunday

%b - sep

%B -december

%m - 09

%Y - 2021

%y - 21


In this article you have learnt how to extract just the year, month, day from an datatime type column using pandas. When you want to summarize your data, give these code snippets a try.


See you in next article, till then keep Learning, keep Exploring.

Comments