Modify datetime Format in pandas DataFrame in Python (2 Examples)

This post explains how to adjust the format of datetime objects in a pandas DataFrame in Python.

Creating Example DataFrame & Importing Module

We can load the pandas library as you can see in the following code:

import pandas as pd

Creating a pandas DataFrame with a datetime column:

x = pd.DataFrame({'Date':['5/15/2023', '6/16/2023', '7/17/2023', '8/18/2023']})
x['Date'] = pd.to_datetime(x['Date'])
print(x)
#         Date
# 0 2023-05-15
# 1 2023-06-16
# 2 2023-07-17
# 3 2023-08-18

Example 1: Adjust pandas DataFrame Column to Year/Month/Day Format

Using the strftime() function to set a date column of pandas DataFrame to a year, month, day order with separating slashes:

x_new_1 = x
x_new_1['New_Date'] = x_new_1['Date'].dt.strftime('%Y/%m/%d')
print(x_new_1)
#         Date    New_Date
# 0 2023-05-15  2023/05/15
# 1 2023-06-16  2023/06/16
# 2 2023-07-17  2023/07/17
# 3 2023-08-18  2023/08/18

Example 2: Adjust pandas DataFrame Column to Another Format

Changing the datetime format within the strftime() function to convert the datetime variable as wanted.

In this case two “-” are added between the date values:

x_new_2 = x
x_new_2['New_Date'] = x_new_2['Date'].dt.strftime('%m--%d--%Y')
print(x_new_2)
#         Date      New_Date
# 0 2023-05-15  05--15--2023
# 1 2023-06-16  06--16--2023
# 2 2023-07-17  07--17--2023
# 3 2023-08-18  08--18--2023

 

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