Home > database >  Convert mm-yyyy to datetime datatype in Python
Convert mm-yyyy to datetime datatype in Python

Time:02-17

I am trying to convert a datetime datatype of the form 24/12/2021 07:24:00 to mm-yyyy format which is 12-2021 with datetime datatype. I need the mm-yyyy in datetime format in order to sort the column 'Month-Year' in a time series. I have tried

import pandas as pd
from datetime import datetime

df = pd.read_excel('abc.xlsx')


df['Month-Year'] = df['Due Date'].map(lambda x: x.strftime('%m-%y'))
df.set_index(['ID', 'Month-Year'], inplace=True)
df.sort_index(inplace=True)
df

The column 'Month-Year' does not sort in time series because 'Month-Year' is of object datatype. How do I please convert 'Month-Year' column to datetime datatype?

CodePudding user response:

df['Month-Year']=pd.to_datetime(df['Month-Year']).dt.normalize()

will convert the Month-Year to datetime64[ns].

Use it before sorting.

CodePudding user response:

I have been able to obtain a solution to the problem.

df['month_year'] = pd.to_datetime(df['birth_date']).dt.to_period('M')

I got this from the link below

https://www.interviewqs.com/ddi-code-snippets/extract-month-year-pandas

  • Related