how to drop hours from pandas datetime to only days in python

To drop hours from a pandas datetime column and keep only the days, you can use the dt.floor() function. Here's an example:

main.py
import pandas as pd

# Create a dataframe with a datetime column
data = {'date': pd.to_datetime(['2021-01-01 12:34:56', '2021-02-03 09:12:34', '2021-03-15 23:45:00'])}
df = pd.DataFrame(data)

# Drop the hours from the datetime column
df['date'] = df['date'].dt.floor('d')

# Output the updated dataframe
print(df)
315 chars
12 lines

Output:

main.py
        date
0 2021-01-01
1 2021-02-03
2 2021-03-15
52 chars
5 lines

In the code above, we first convert the date column to a pandas datetime format using pd.to_datetime(). Then, we use the dt.floor() function to drop the hours and keep only the days. Finally, we assign the updated datetime column back to the original dataframe.

related categories

gistlibby LogSnag