Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (17.6k points)

I'm trying to extract year/date/month info from the 'date' column in the pandas dataframe. Here is my sample code:

from datetime import datetime

def date_split(calendar):

  for row in calendar: 



I haven't finished the complete code, but when I test run this part I keep getting error like this:

----> 7         listdate=datetime.strptime(row['date'],'%Y-%M-%D')

TypeError: string indices must be integers

Anyone has any idea?

Btw, this is the dataframe I use (calendar_data):

enter image description here

1 Answer

0 votes
by (41.4k points)


To extract day/year/month from pandas dataframe, use to_datetime as depicted in the below code:

print (df['date'].dtype)



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


print (df['date'].dtype)


For extracting year,month and day to new column,follow the code:

df['year'] = df['date'].dt.year

df['month'] = df['date'].dt.month

df['day'] = df['date']

If you wish to learn more about Python, visit Python tutorial and Python course by Intellipaat.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories