I am working on Time Series so I want to convert object type to datetime. I have a data frame like this:
trxyear trxmonth
0 2014 JUL-13
1 2014 JUL-13
2 2014 JUL-13
3 2014 JUL-13
4 2014 JUL-13
... ... ...
46394 2023 SEP-22
46395 2023 SEP-22
46396 2023 SEP-22
46397 2023 SEP-22
46398 2023 SEP-22
I want to convert trxmonth
to datetime so I can apply time series. but when I convert using this code
CODE:
from dateutil import parser
print(parser.parse("JUL-13"))
OUTPUT:
2022-07-13 00:00:00
but it can convert July 2013
to 13 July 2022
.
CODE:
print(parser.parse("01-JUL-13") )
OUTPUT:
2013-07-01 00:00:00
when I use this code it can converts correctly but my data is not in this format.
Simply I want to convert JUL-13
--> 01-07-2013
CodePudding user response:
Use to_datetime
with format
parameter:
df['trxmonth'] = pd.to_datetime(df['trxmonth'], format='%b-%y')
print (df)
trxyear trxmonth
0 2014 2013-07-01
1 2014 2013-07-01
2 2014 2013-07-01
3 2014 2013-07-01
4 2014 2013-07-01
46394 2023 2022-09-01
46395 2023 2022-09-01
46396 2023 2022-09-01
46397 2023 2022-09-01
46398 2023 2022-09-01