Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with .dt accessor even after confirming Timestamp datatype in pandas DataFrame

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading