Set pandas DataFrame Column to datetime in Python (Example)

This post shows how to convert a pandas DataFrame column to the datetime class in the Python programming language.

Loading pandas Module & Creating Example Data

For our example, we first need to load the pandas library:

import pandas as pd

The exemplifying DataFrame below will be used for this tutorial:

x = pd.DataFrame({'Date':['3/18/2023', '5/18/2025', '4/6/2022', '9/14/2024', '4/25/2024']})
print(x)
#         Date
# 0  3/18/2023
# 1  5/18/2025
# 2   4/6/2022
# 3  9/14/2024
# 4  4/25/2024

Example 1: Applying pandas.to_datetime()

To convert a variable of a pandas DataFrame to datetime we can apply the to_datetime() function as shown below:

x_new = x
x_new['Date'] = pd.to_datetime(x_new['Date'])
print(x_new)
#         Date
# 0 2023-03-18
# 1 2025-05-18
# 2 2022-04-06
# 3 2024-09-14
# 4 2024-04-25

The Python syntax above has created a new DataFrame object with our input dates formatted as datetime.

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top