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 |
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 |
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 |
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.
- Modify datetime Format in pandas DataFrame in Python (2 Examples)
- Retain Only Date Part when Using pandas.to_datetime in Python
- Transform datetime Object to Date & Vice Versa in Python (2 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.