I am encountering an AttributeError when trying to use the .dt accessor on a pandas Series, despite confirming that the Series contains only Timestamp objects. I’ve condensed my problem into a Minimal Reproducible Example (MRE) below:
import pandas as pd
# Sample data
data = {'DateGreffe': ['25/10/2023', '26/10/2023', '27/10/2023']}
df = pd.DataFrame(data)
# Convert "DateGreffe" to datetime
df.loc[:, "DateGreffe"] = pd.to_datetime(df["DateGreffe"], dayfirst=True)
# Check data type of "DateGreffe" column
print(df["DateGreffe"].apply(type).unique())
# Convert "DateGreffe" back to string format "DD/MM/YYYY"
df.loc[:, "DateGreffe"] = df["DateGreffe"].dt.strftime("%d/%m/%Y")
print(df)
The output of the print statement confirms that the DateGreffe column only contains Timestamp objects. However, when I try to use .dt.strftime on this column, I get the following error:
AttributeError: Can only use .dt accessor with datetimelike values
>Solution :
When you assign with a slicing on the rows like:
df.loc[:, "DateGreffe"] = pd.to_datetime(df["DateGreffe"], dayfirst=True)
This keeps the original type of the Series (if possible), here object.
df["DateGreffe"].dtype
# dtype('O')
To fix it, assign the whole column without slicing the rows with :
:
df["DateGreffe"] = pd.to_datetime(df["DateGreffe"], dayfirst=True)
df["DateGreffe"].dtype
# dtype('<M8[ns]')