Convert pandas DataFrame Column to datetime in Python (Example)

 

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

Table of content:

Let’s dive straight into the Python code!

 

Loading pandas Module & Creating Example Data

For this tutorial, we first need to load the pandas library to Python:

import pandas as pd

Next, we can create an exemplifying DataFrame as shown below:

data = pd.DataFrame({'Date':['1/15/2021', '1/27/2023', '7/3/2020', '1/26/2022', '4/25/2024']})
print(data)
#         Date
# 0  1/15/2021
# 1  1/27/2023
# 2   7/3/2020
# 3  1/26/2022
# 4  4/25/2024

Our example DataFrame contains dates, but these dates are formatted as character strings.

 

Example 1: Using pandas.to_datetime()

This example explains how to convert a variable of a pandas DataFrame to datetime.

To achieve this, we can apply the to_datetime() function as shown below:

data_new = data
data_new['Date'] = pd.to_datetime(data_new['Date'])
print(data_new)
#         Date
# 0 2021-01-15
# 1 2023-01-27
# 2 2020-07-03
# 3 2022-01-26
# 4 2024-04-25

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

 

Video, Further Resources & Summary

Do you need more explanations on how to change a pandas DataFrame column to datetime in Python? Then you may take a look at the following YouTube video from the YouTube channel of Corey Schafer.

In the video, the speaker explains how to work with date and time series data in Python.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Of course, you can also have a look at some of the other tutorials on Statistics Globe:

This tutorial has shown how to change and set the data type of a pandas DataFrame column to datetime in the Python programming language. In case you have further questions, please leave a comment below.

 

Gottumukkala Sravan Kumar Statistician & Programmer

Note: This article was created in collaboration with Gottumukkala Sravan Kumar. Gottumukkala is a data analyst and programmer who helps to create tutorials on topics such as the datetime module in Python. You may find more information about Gottumukkala and his other articles on his profile page.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top