| by Arround The Web | No comments

Pandas Convert Column to DateTime

The widely used data structure of Pandas library named “DataFrame” can also be used to work with date and time data. To manipulate or analyze the date and time data easily and efficiently in Pandas, we need to represent them as a DateTime object. To do this conversion from different column types to DateTime objects, various methods are used in Python.

This tutorial will provide the procedure for converting DataFrame columns to DateTime objects.

How to Convert a Column to DateTime Object in Python?

The below methods are utilized to convert the column of DataFrame to a DateTime object using numerous examples:

Method 1: Convert Column to DateTime Object Using the “pd.to_datetime()” Method

The “pd.to_datetime()” method is used in Python to convert the given DataFrame column to a DateTime object. Here is the syntax:

pandas.to_datetime(arg, errors='raise', utc=False, format=None, exact=_NoDefault.no_default, unit=None,dayfirst=False, yearfirst=False infer_datetime_format=_NoDefault.no_default, origin='unix', cache=True)

 

For a detailed understanding of this method, please check our dedicated article.

Example 1: Convert Single Column to DateTime Object

The below code converts the single column to a DateTime object:

import pandas
df = pandas.DataFrame({'Courses':['Python', 'Java', 'C++'],'Starting Date':['5/21/2023', '3/24/2028', '5/20/2023']})
print(df, '\n')
print(df.dtypes, '\n')
df['Starting Date']= pandas.to_datetime(df['Starting Date'])
print(df, '\n')
print(df.dtypes)

 

Here in this code, the “pandas.DataFrame()” function creates the DataFrame with the DateTime object column. After that, the “pandas.to_datetime()” method converts the DataFrame column “Starting Date” to a DateTime object. The “df.dtypes” is used to retrieve the type of DataFrame columns.

Output

The column “Starting Date” has been converted/transformed into a DateTime object.

Example 2: Convert Multiple Columns to DateTime Object

The following code is used to convert the multiple columns to the DateTime object:

import pandas
df = pandas.DataFrame({'Courses':['Python', 'Java', 'C++'],'Starting Date':['5/21/2023', '3/24/2028', '5/20/2023'],
'Ending Date':['2/11/2023', '5/21/2025', '6/11/2022']})
print(df, '\n')
print(df.dtypes, '\n')
df['Starting Date']= pandas.to_datetime(df['Starting Date'])
df['Ending Date']= pandas.to_datetime(df['Ending Date'])
print(df, '\n')
print(df.dtypes)

 

In this code, the “pandas.to_datetime()” method is used twice to convert the “Starting Date” and “Ending Date” columns to the DateTime object.

Output

The column “Starting Date” and “Ending Date” have been converted into a DateTime object.

Example 3: Convert Columns to DateTime Object by Specifying the Format

Check out the below-provided code for converting columns to the DateTime object using the specified format:

import pandas
df = pandas.DataFrame({'Courses':['Python', 'Java', 'C++'],'Starting Date':['230512', '230714', '230221']})
print(df, '\n')
print(df.dtypes, '\n')
df['Starting Date']= pandas.to_datetime(df['Starting Date'], format='%y%m%d')
print(df, '\n')
print(df.dtypes)

 

In the above code, the specified format “%y%m%d” is passed to the “pandas.to_datetime()” method to convert/transform the DataFrame column to the DateTime object based on the format.

Output

The DataFrame column based on the specified format has been transformed into a DateTime object.

Method 2: Convert Column to DateTime Object Using the “df.astype()” Method

The “df.astype()” method of the Pandas module is used to convert the Pandas object to the specified object, such as “DateTime”. Here is the syntax of this method:

DataFrame.astype(dtype, copy=None, errors='raise')

 

Check this dedicated guide to understand this method in detail. Here is an example code that converts/transforms the column to a DateTime object:

import pandas
df = pandas.DataFrame({'Courses':['Python', 'Java', 'C++'],'Starting Date':['5/21/2023', '3/24/2028', '5/20/2023']})
print(df, '\n')
print(df.dtypes, '\n')
df['Starting Date'] = df['Starting Date'].astype('datetime64[ns]')
print(df, '\n')
print(df.dtypes)

 

According to the above code, the “df.astype()” method takes the datatype “datetime64” as an argument and converts the specified DataFrame column to a DateTime object.

Output

The specified column has been converted into the DateTime object.

Method 3: Convert Column to DateTime Object Using the “df.apply()” and “lambda” Function

We can also use the “df.apply()” method along with the “lambda” function to convert the column to a DateTime object. Here is a code snippet that illustrates this method:

import pandas, datetime
df = pandas.DataFrame({'Courses':['Python', 'Java', 'C++'],'Starting Date':['05/12/2023', '03/11/2028', '05/12/2023']})
print(df, '\n')
print(df.dtypes, '\n')
df['Starting Date'] = df['Starting Date'].apply(lambda _: datetime.datetime.strptime(_,"%d/%m/%Y"))
print(df, '\n')
print(df.dtypes)

 

In this code, the “apply()” method is used to apply the lambda function to the DataFrame column by utilizing the “datetime.datetime.strptime()” method. This method retrieves the DateTime object representation of the specified DataFrame column.

Output

The specified DataFrame column has been converted into a DateTime object.

Conclusion

The “pd.to_datetime()”, “df.astype()”, and the “df.apply()” with “lambda” methods are used to convert columns to DateTime objects in Python. The “pd.to_datetime()” method is utilized for converting the single or multiple columns to the DateTime object based on the specified format. The other method can also be used to convert/transform the column to DateTime. This write-up presented about converting DataFrame columns to DateTime.

Share Button

Source: linuxhint.com

Leave a Reply