Shulaz Shan
Shulaz Shan

Reputation: 175

convert to date time format

I have column Monthyear(dtype = object), I want to convert to Date time formate.

I tried below this code, but it is not working.....

AGENT       MONTHYEAR

45          SEP-2018
567         AUG-2017
432         APR-2018  
Reatiers_Sales_Monthlywises_above_13['MONTHYEARS'] = Reatiers_Sales_Monthlywises_above_13['MONTHYEAR'].apply(lambda x: x.strftime('%B-%Y'))
Reatiers_Sales_Monthlywises_above_13
```

Pls support to convert this object dtype to DateTime

Upvotes: 0

Views: 55

Answers (2)

Andy L.
Andy L.

Reputation: 25239

IF you want to keep it in year-month format, you need to convert it to period dtype.

pd.to_datetime(df.MONTHYEAR).dt.to_period('M')

Out[206]:
0    2018-09
1    2017-08
2    2018-04
Name: MONTHYEAR, dtype: period[M]

If you want it in Datetime dtype, it will be in the format of year-month-date

pd.to_datetime(df.MONTHYEAR)

Out[207]:
0   2018-09-01
1   2017-08-01
2   2018-04-01
Name: MONTHYEAR, dtype: datetime64[ns]

Note: strftime in your apply will convert it to string/object dtype, so I don't know whether that is your intention to use it.

Upvotes: 2

tawab_shakeel
tawab_shakeel

Reputation: 3739

Try using dateutil parser

It will convert string into date

NOTE: it adds 03 as a day because current day is 03

from dateutil import parser

df = pd.DataFrame(data={"AGENT":[45,567,432],
                   "MONTHYEAR":['SEP-2018','AUG-2017','APR-2018']})


df['MONTHYEAR'] = df['MONTHYEAR'].apply(lambda x :parser.parse(str(x)))

     AGENT  MONTHYEAR
0     45    2018-09-03
1    567    2017-08-03
2    432    2018-04-03

Upvotes: 0

Related Questions