Search code examples
pythonpython-3.xpandasdatetimeattributeerror

Combining and Grouping By Dates using a Pandas Dataframe


I have a data column in my Pandas data frame that looks like the following:

Date
========
2022-01-01T00:00:00.000Z
2022-01-01T08:00:00.000Z    
2022-01-01T16:00:00.000Z
2022-01-02T00:00:00.000Z
2022-01-02T08:00:00.000Z    
2022-01-02T16:00:00.000Z    

I am trying to reformat the dates into %Y-%m-%d form, so I can perform a groupby operation on the dates.

I am currently trying to run this line of code

CombinedData['Date'] = CombinedData['Date'].dt.strftime("%Y-%m-%d")

but I keep getting an AttributeError: Can only use .dt accessor with datetimelike values. I am a little confused on why this error is occurring since my dates are formatted as dates in my data frame. Why is this happening, and what can I do to mend this issue?


Solution

  • Use:

    CombinedData['Date'] = pd.to_datetime(CombinedData['Date']).dt.strftime("%Y-%m-%d")