Home > Enterprise >  How to change data type of dataframe column to date when it consists of month and year?
How to change data type of dataframe column to date when it consists of month and year?

Time:12-06

I have got a column which includes dates in the format of (Year-Month), and I want to convert the data type to date. I have tried using date_sr.dt.strftime('%Y,%m') but gives me an error "Can only use .dt accessor with datetimelike values". I have printed the dates and are like "2022-11" of type string.

patentfile['Application Year/Month'] = patentfile['Application Year/Month'].dt.strftime('%Y,%m')

CodePudding user response:

It looks like in your code, you are trying to use the strftime method on the entire column of dates at once, but this will not work because the strftime method is not defined for a column of data. You will need to apply the strftime method to each individual date in the column. Here is an example of how you can do this using the apply method:

# Convert each date in the column to a date object
date_objects = patentfile['Application 
Year/Month'].apply(lambda x: datetime.strptime(x, '%Y-%m'))

# Convert each date object to a string in the desired format
formatted_dates = date_objects.apply(lambda x: 
x.strftime('%Y,%m'))

# Update the column with the formatted dates
patentfile['Application Year/Month'] = formatted_dates

This code will convert each date in the 'Application Year/Month' column from a string to a date object, then convert each date object to a string in the desired format, and finally update the column with the formatted dates.

  • Related