Use the following snippet to convert a datetime column to the date data type:
your_df['just_date']= your_df['date'].dt.date
Alternatively, use the strftime formatting function to convert your datetime values to a formatted date string, for example”
your_df['formatted_date']= hr['date'].dt.strftime('%d/%m/%y')
Convert datetimes to date format – Practical example
Step 1: Define your data
We will start by importing the pandas package and defining a very simple pandas DataFrame. We will use the date_range pandas function to create three datetime values. We will then save them as a column in a pandas DataFrame object.
import pandas as pd
dates = pd.date_range(start='5/1/24 12:30:00', periods=3,)
interviews = [144, 123, 87]
hr = pd.DataFrame(dict(datetime=dates, interviews =interviews))
print (hr)
Here is our DataFrame:
datetime | interviews | |
---|---|---|
0 | 2024-05-01 12:30:00 | 144 |
1 | 2024-05-02 12:30:00 | 123 |
2 | 2024-05-03 12:30:00 | 87 |
Step 2: Convert datetime column to date
Next, we can use the dt pandas Series accesor to quickly get the date only format from the datetime column:
hr['short_date']= hr['datetime'].dt.date
A new column named short_date will be create in our DataFrame, showing the date in yyyy-mm-dd format:
datetime | interviews | short_date | |
---|---|---|---|
0 | 2024-05-01 12:30:00 | 144 | 2024-05-01 |
1 | 2024-05-02 12:30:00 | 123 | 2024-05-02 |
2 | 2024-05-03 12:30:00 | 87 | 2024-05-03 |
Step 3: Format datetime as a string
What is we would like to format our dates ass dd-mm-yyyy or other formats? If so, we use the strftime function as shown below:
hr['formatted_date']= hr['date'].dt.strftime('%d/%m/%y')
Note: Always make sure to to use the dt accessor before running strftime on your Series. Failing to do so will lead to an Attributeerror with strftime.