Home > OS >  Converting/Modifying non-standard string into datetime for Python DataFrame
Converting/Modifying non-standard string into datetime for Python DataFrame

Time:12-23

So I have a set of data for sales by month (not in order) but the string format for the data column comes out as month/day/year hour:minute

For example: 04/19/19 18:27 and it is a string object.

How am I able to convert this into datetime where I only take the month and day?

Also, how can I simply take only the month and convert it to an integer?

CodePudding user response:

To convert it to a datetime, use pd.to_datetime():

df['date'] = pd.to_datetime(df['date'], format="%m/%d/%y %H:%M")

To get the month out of it, use this after you've run the above:

df['month'] = df['date'].dt.month

To convert it into a YYYY-MM format:

df['year-month'] = df['a'].dt.strftime('%Y-%m')

As we discussed in chat, this wasn't working because the column names were copied as rows into the dataframe at various points.

  • Related