Retain Only Date Part when Using pandas.to_datetime in Python

This post explains how to keep only the date part when using pandas.to_datetime in Python.

Generate Example DataFrame & Load pandas Module

At the beginning, we have to load the pandas Module:

import pandas as pd

Then we can create a DataFrame with datetime column as shown below:

x = pd.DataFrame({'date':['4-23-2027 13:09:26',
                             '6-8-2025 15:24:34',
                             '8-12-2026 7:33:18',
                             '12-30-2028 20:8:3',
                             '1-16-2024 8:7:55'],
                    'value':[8, 4, 3, 7, 3]})
x['date'] = pd.to_datetime(x['date'])
print(x)
#                  date  value
# 0 2027-04-23 13:09:26      8
# 1 2025-06-08 15:24:34      4
# 2 2026-08-12 07:33:18      3
# 3 2028-12-30 20:08:03      7
# 4 2024-01-16 08:07:55      3

Example: Delete Time Component from datetime Column in pandas DataFrame

To retain only the date of a datetime variable of our date column we can use the date attribute:

x_new = x
x_new['date'] = x_new['date'].dt.date
print(x_new)
#          date  value
# 0  2027-04-23      8
# 1  2025-06-08      4
# 2  2026-08-12      3
# 3  2028-12-30      7
# 4  2024-01-16      3

 

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