-2

good Evening, I have a dataframe which consists of order date, dispatch date each having dates in the format 02-25-2013. I want to extract month and year from these dates and I want to generate new columns in my dataset as Order_Mt, Order_yr, Dispatch_Mt, Dispatch_Yr. I tried to extract by using strptime(). But no use. Can anyone tell me how to do this?

Thanks in advance

molbdnilo
  • 64,751
  • 3
  • 43
  • 82

1 Answers1

0

Use .dt to access the datetime methods.

Ex:

import pandas as pd
df = pd.DataFrame({'Order Date': ["02-25-2013"]})
df["Order Date"] = pd.to_datetime(df["Order Date"])
df["Order_Mt"] = df["Order Date"].dt.month
df["Order_yr"] = df["Order Date"].dt.year
print(df)

Output:

  Order Date  Order_Mt  Order_yr
0 2013-02-25         2      2013
Rakesh
  • 81,458
  • 17
  • 76
  • 113