Pandas DataFrame: Convert the column type from string to datetime format
While working with data in Pandas, it is not an unusual thing to encounter time series data and we know Pandas is a very useful tool for working with time series data in Python.
Let’s see how we can convert a DataFrame column of strings (in dd/mm/yyyy format) to datetime format. We cannot perform any time series based operation on the dates if they are not in the right format. In order to be able to work with it, we are required to convert the dates into the datetime format.
Convert Pandas DataFrame column type from string to datetime format using pd.to_datetime() function.
#importing pandas as pd import pandas as pd # Creating the dataframe d = pd.DataFrame({'Date':['11/8/2011', '04/23/2008', '10/2/2019'], 'Event':['Music', 'Poetry', 'Theatre'], 'Cost':[10000, 5000, 15000]}) d
d.info()
d['Date']= pd.to_datetime(d['Date']) d.info()
print(d.Date[0].day) print(d.Date[0].month) print(d.Date[0].year)
Follow Me on Twitter and LinkedIn