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 |
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 |
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 |
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.
- Modify datetime Format in pandas DataFrame in Python (2 Examples)
- Set pandas DataFrame Column to datetime in Python (Example)
- Get Year, Month & Day Separately from datetime Object in Python (3 Examples)
- How to Add Days, Months & Years to a datetime Object in Python (3 Examples)
- All Python Programming Tutorials
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.