Search code examples
pythonpandasdatetimeone-liner

How to extract month and year from a datetime series and store them into two separate columns?


I have a dataframe with a Date column that has datetime objects in it. I can extract the month and year from the Date column and store them in columns of the respective names using the code below.

df["Month"] = df["Date"].dt.month
df["Year"] = df["Date"].dt.year

But is there a way to do this in just one line?


Solution

  • Here's how you can do it:

    df['Month'], df['Year'] = df["Date"].dt.month, df["Date"].dt.year