cs95
cs95

Reputation: 402323

Parsing week of year to datetime objects with pandas

     A    B    C     D yearweek
0  245   95   60    30  2014-48
1  245   15   70    25  2014-49
2  150  275  385   175  2014-50
3  100  260  170   335  2014-51
4  580  925  535  2590  2015-02
5  630  126  485  2115  2015-03
6  425   90  905  1085  2015-04
7  210  670  655   945  2015-05

The last column contains the the year along with the weeknumber. Is it possible to convert this to a datetime column with pd.to_datetime?

I've tried:

pd.to_datetime(df.yearweek, format='%Y-%U')

0   2014-01-01
1   2014-01-01
2   2014-01-01
3   2014-01-01
4   2015-01-01
5   2015-01-01
6   2015-01-01
7   2015-01-01
Name: yearweek, dtype: datetime64[ns]

But that output is incorrect, while I believe %U should be the format string for week number. What am I missing here?

Upvotes: 3

Views: 1467

Answers (1)

jezrael
jezrael

Reputation: 862511

You need another parameter for specify day - check this:

df = pd.to_datetime(df.yearweek.add('-0'), format='%Y-%W-%w')
print (df)
0   2014-12-07
1   2014-12-14
2   2014-12-21
3   2014-12-28
4   2015-01-18
5   2015-01-25
6   2015-02-01
7   2015-02-08
Name: yearweek, dtype: datetime64[ns]

Upvotes: 4

Related Questions