To extract the date portion from a timestamp column in a Pandas DataFrame containing hours, minutes, and seconds, you can utilize the 'dt.date' method. This method effectively separates the date component from the time component within the timestamp, creating a new column containing only the dates.

Here's an example code demonstrating how to achieve this:

import pandas as pd

# Create a DataFrame with a datetime column
df = pd.DataFrame({'datetime': ['2022-01-01 10:30:00', '2022-01-02 15:45:00', '2022-01-03 08:15:00']})

# Convert the datetime column to datetime type and extract the date part
df['date'] = pd.to_datetime(df['datetime']).dt.date

# Print the resulting DataFrame
print(df)

The output will be:

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

In this code snippet, we first create a DataFrame containing a 'datetime' column with timestamp values. Next, we convert the 'datetime' column to datetime type using 'pd.to_datetime' and extract the date component using the 'dt.date' method, storing it in a new 'date' column. Finally, we print the DataFrame, showcasing the original timestamp and the extracted date in separate columns.

Pandas: Extract Date from Timestamp Column

原文地址: https://www.cveoy.top/t/topic/fOkj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录