Convert pandas Dataframe Column type from string to datetime
Here in this tutorial, we will see how to convert pandas Dataframe Column type from string to DateTime.
So if we take a look at the type of dataframe created without any particular specifications then it will look something like this:
import pandas as pd tableDF = pd.DataFrame({'Date':['01/02/2001', '17/11/2012', '27/07/2022']}) print(tableDF.info())
So here after importing pandas, we have created a dataframe named ‘tableDF’ with some dates within, and then we have printed its information which will tell us its type.
Output:
Data columns (total 1 columns): # Column Non-Null Count Dtype - ------ -------- ----- ----- 0 Date 3 non-null object dtypes: object(1) memory usage: 152.0+ bytes
So if we look at the Dtype it says object but we need to convert this into DateTime.
Using to_datetime() function
import pandas as pd tableDF = pd.DataFrame({'Date':['01/02/2001', '17/11/2012', '27/07/2022']}) tableDF['Date'] = pd.to_datetime(tableDF.Date) print(tableDF.info())
Output:
Data columns (total 1 columns):
# Column Non-Null Count Dtype
- ------ -------- ----- -----
0 Date 3 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 152.0 bytes
Here now the type is being changed from object to DateTime.
Leave a Reply