Convert the column type from string to datetime format in Pandas dataframe.



Let`s see how we can convert a column of data rows (in dd / mm / yyyy format) to date and time format. We cannot perform any time series operations with dates if they are not formatted correctly. To be able to work with it, we must convert dates to datetime format.

Code # 1: Convert the Pandas data column type from string format to datetime format using pd .to_datetime () .

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ ` Date` : [ `11 / 8 / 2011` , `04/23 / 2008` , `10/2 / 2019` ],

  ` Event` : [ `Music` , `Poetry` , `Theater` ],

  ` Cost` : [ 10000 , 5000 , 15000 ]})

 
# Print the data frame

print (df)

 
# Now we check the data type
Column # "Date"
df.info ()

Output:


As we can see in the output, the data type of the Date column is — it is an object, that is, a string. We now convert it to datetime format using pd.to_datetime () .

# convert the “Date” column to date format and time

df [ `Date` ] = pd.to_datetime (df [ `Date` ])

 
# Check column format "Date"
df.info ()

Output:

As we can see in the output, the Date column format has been changed to date and time format.

Code # 2: Convert the Pandas data column type from string to date and time format using DataFrame.astype () .

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ `Date` : [ `11/8 / 2011` , ` 04/23 / 2008` , `10/2 / 2019` ],

`Event` : [ `Music` , ` Poetry`  , `Theater` ],

`Cost` : [ 10000 , 5000 , 15000 ]})

 
# Print data frame

print (df)

 
# Now we check the data type
No. of column "Date"
df.info ()

Output:

As we can see in the output, the data type of the Date column is — it is an object, that is, a string. We now convert it to datetime format using DataFrame.astype () .

# convert the column “Date” to date format and time

df [ `Date` ] = df [ `Date` ]. astype ( `datetime64 [ns]` )

 
# Check the format of the "Date" column
df. info ()

Output:

As we can see in the output, the format of the Date column has been changed to date and time.