How to Convert Datetime to Date in Pandas?

How to Convert Datetime to Date in Pandas?

If you have a pandas DataFrame with a column containing datetime objects and you want to extract just the date component, you can do so using the dt accessor. Here's how you can convert a datetime to a date in pandas:

Let's consider you have a DataFrame df with a column 'datetime_column' that contains datetime values.

import pandas as pd # Sample data df = pd.DataFrame({ 'datetime_column': ['2021-07-01 14:58:00', '2021-07-02 15:10:00', '2021-07-03 16:20:00'] }) # Convert the 'datetime_column' to datetime dtype df['datetime_column'] = pd.to_datetime(df['datetime_column']) # Extract the date from the datetime dtype df['date_column'] = df['datetime_column'].dt.date print(df) 

Output:

 datetime_column date_column 0 2021-07-01 14:58:00 2021-07-01 1 2021-07-02 15:10:00 2021-07-02 2 2021-07-03 16:20:00 2021-07-03 

As shown, the 'date_column' now contains only the date component of the 'datetime_column'.


More Tags

touches mount android-contentresolver proxy dbunit bookshelf.js ruby-on-rails-3.2 out-of-memory deploying intersection

More Programming Guides

Other Guides

More Programming Examples