1

I'm working with COVID19 data and have a date column. It was originally as Int64, so I changed it to datetime object using the below function:

us['date'] = pd.to_datetime(us['date'], format='%Y%m%d', errors='ignore')
us['date'] = us['date'].dt.strftime("%m/%d")

When I print out the result, I see all the data in the column as "1/1, 1/4, 2/1 ....", so on. (There is no null value here) I'm trying to use group this by month, so I tried to use another function to get only months as below:

us['date'].dt.strftime("%m")

But I'm getting the error:

AttributeError: Can only use .dt accessor with datetimelike values

I don't understand, since I change the datatype to datetime using pd_datetime, should this column already be datetime, not object? When I checked the data type, it shows 'O'. Why is this so?

3
  • Can you post sample data? Commented Aug 16, 2020 at 19:51
  • Try posting some sample data covering all formats of us['date'] prior any manipulation. Commented Aug 16, 2020 at 20:19
  • "It was originally as Int64" - then parsing with format='%Y%m%d' doesn't make much sense to me - instead, this should require you to supply a unit, e.g. unit='s' if the datetime data is represented as UNIX time / seconds since the epoch. Commented Aug 17, 2020 at 6:56

2 Answers 2

1

When we do ignore ,it will ignore the whole column if any item can not be changed ,we should do coerce

us['date'] = pd.to_datetime(us['date'], format='%Y%m%d', errors='coerce')
us['date'].dt.strftime('%B')
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I still get the exact same attribute error.......
@sarahkim let us drop na value ~
Yes I changed to coerce and tried, same error. pd.to_datetime worked perfectly fine. I changed from 20200101 string --> 2020-01-01 datetime successfully. From here I tried to extract the month 2020-01-01 --> January, is where I'm failing...
@sarahkim us['date'].dt.strftime('%B') ?
0

Lets try this:

us['monthanddate'] = us['date'].dt.strftime("%m/%d")

For only month

us['monthonly'] = us['date'].dt.strftime("%m")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.