Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to datetime in pandas

Tags:

python

pandas

I have the foll. list in pandas:

str = jan_1 jan_15  feb_1   feb_15  mar_1   mar_15  apr_1   apr_15  may_1   may_15  jun_1   jun_15  jul_1   jul_15  aug_1   aug_15  sep_1   sep_15  oct_1   oct_15  nov_1   nov_15  dec_1   dec_15

Is there a way to convert it into datetime?

I tried: pd.to_datetime(pd.Series(str))

like image 403
user308827 Avatar asked Feb 09 '23 05:02

user308827


1 Answers

You have to specify the format argument while calling pd.to_datetime. Try

pd.to_datetime(pd.Series(s), format='%b_%d')

this gives

0   1900-01-01
1   1900-01-15
2   1900-02-01
3   1900-02-15
4   1900-03-01
5   1900-03-15
6   1900-04-01
7   1900-04-15
8   1900-05-01
9   1900-05-15

For setting the current year, a hack may be required, like

pd.to_datetime(pd.Series(s) + '_2015', format='%b_%d_%Y')

to get

0   2015-01-01
1   2015-01-15
2   2015-02-01
3   2015-02-15
4   2015-03-01
5   2015-03-15
6   2015-04-01
7   2015-04-15
8   2015-05-01
9   2015-05-15
like image 50
Sandeep S Avatar answered Feb 12 '23 12:02

Sandeep S