How to Convert Datetime to Date in Pandas?


In data analysis and manipulation, dealing with dates and times is a common requirement. The Pandas library in Python provides powerful tools for working with datetime values. In this article, we will explore the process of converting datetime values to date−only format in a Pandas DataFrame.

When working with datetime values, it is often necessary to extract specific components, such as the year, month, day, or time, for further analysis or visualisation. However, in some cases, we may only be interested in the date portion of the datetime object, excluding the time information.

Converting datetime values to date−only format can be useful in various scenarios. For instance, when aggregating data by date, removing the time component simplifies the analysis and allows us to focus solely on the date dimension. Additionally, when merging or joining datasets based on dates, converting datetime values to dates can help align the data more effectively.

In this article we will explore different approaches to convert datetime values to date format in a Pandas DataFrame. We will demonstrate both the direct method using Pandas' built−in functions and a custom function for more specific requirements.

Now let's discuss the different approaches with which we can convert datetime to date in pandas.

Using the dt Accessor

Pandas provides a convenient dt accessor, which allows us to access various components of datetime values. To convert datetime values to date format using this approach, we can use the date property of the dt accessor.

Let's see how it works:

Example

import pandas as pd

# Create a sample DataFrame with datetime values
data = {'datetime': ['2022-01-01 10:30:00', '2022-02-15 14:45:00', '2022-03-20 18:00:00']}
df = pd.DataFrame(data)

# Convert 'datetime' column to datetime type
df['datetime'] = pd.to_datetime(df['datetime'])

# Extract date using the 'dt' accessor
df['date'] = df['datetime'].dt.date

# Display the DataFrame
print(df)

Explanation

  • Firstly, we import the required Pandas library.

  • Next, we create a sample DataFrame with datetime values in the 'datetime' column.

  • To perform datetime operations, we need to convert the 'datetime' column to the datetime type using the pd.to_datetime() function.

  • Using the dt accessor, we access the 'datetime' column and use the date property to extract only the date component.

  • We assign the extracted date values to a new column called 'date'.

  • Finally, we print the DataFrame to see the result.

Output

             datetime        date
0 2022-01-01 10:30:00  2022-01-01
1 2022-02-15 14:45:00  2022-02-15
2 2022-03-20 18:00:00   2022-03-20

Using the apply() Function

Another approach to converting datetime values to date format involves using the apply() function along with a lambda function. This approach provides flexibility when we have specific formatting requirements.

Here's how we can achieve this:

Example

import pandas as pd

# Create a sample DataFrame with datetime values
data = {'datetime': ['2022-01-01 10:30:00', '2022-02-15 14:45:00', '2022-03-20 18:00:00']}
df = pd.DataFrame(data)

# Convert 'datetime' column to datetime type
df['datetime'] = pd.to_datetime(df['datetime'])

# Define a custom function to extract date
def extract_date(dt):
    return dt.date()

# Apply the custom function to the 'datetime' column
df['date'] = df['datetime'].apply(extract_date)

# Display the DataFrame
print(df)

Explanation

  • We import the necessary Pandas library.

  • Next, we create a sample DataFrame with datetime values.

  • Similar to the previous approach, we convert the 'datetime' column to the datetime type using pd.to_datetime().

  • We define a custom function, extract_date(), which takes a datetime value as input and returns only the date component using the date() function.

  • Using the apply() function, we apply the extract_date() function to each element of the 'datetime' column and assign the results to a new column called 'date'.

  • Finally, we print the DataFrame to observe the outcome.

Output

             datetime        date
0 2022-01-01 10:30:00  2022-01-01
1 2022-02-15 14:45:00  2022-02-15
2 2022-03-20 18:00:00   2022-03-20

Conclusion

In conclusion, converting datetime to date in Pandas is a common task when working with time series data or analysing temporal information. In this article, we explored two different approaches to accomplish this task.

The first approach involved using the dt accessor in Pandas, which provides convenient methods for accessing and manipulating datetime components.

The second approach involved using the to_datetime function in Pandas to convert the datetime column to a datetime data type, and then using the dt accessor to extract the date component.

With the insights gained from this article, you can confidently handle datetime to date conversions in Pandas and streamline your data analysis workflows.

Updated on: 03-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements