8

Sample Data:

Week      Price
2011-31    1.58
2011-32    1.9
2011-33    1.9
2011-34    1.9

I have a dataframe like above and I wanna convert 'Week' column type from string to datetime.

My Code:

data['Date_Time'] = pd.to_datetime(data.Week, format='%Y-%W')
data = data.drop(['Week'], axis=1)
data.index = data.Date_Time

Error:

'ValueError: Cannot use '%W' or '%U' without day and year'

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Emre BEGEN
  • 577
  • 1
  • 7
  • 17

2 Answers2

9

You need specify day of week by parameter %w:

data['Date_Time'] = pd.to_datetime(data.Week + '0', format='%Y-%W%w')
print (data)
      Week  Price  Date_Time
0  2011-31   1.58 2011-08-07
1  2011-32   1.90 2011-08-14
2  2011-33   1.90 2011-08-21
3  2011-34   1.90 2011-08-28

For DatetimeIndex use DataFrame.pop with rename:

data.index = pd.to_datetime(data.pop('Week') + '0', format='%Y-%W%w').rename('Date')
print (data)
            Price
Date             
2011-08-07   1.58
2011-08-14   1.90
2011-08-21   1.90
2011-08-28   1.90
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

%W uses Monday as the first day of the week.

import datetime
week = '2011-31'
date=datetime.datetime.strptime(week + '-1', "%Y-%W-%w")
print(date)

See this:https://repl.it/@ibrahimth/EvergreenNutritiousEmbeds

I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37
  • OK, so simple question - Do you think your answer working for OP, he/she need `How to convert string dataframe column to datetime as format with year and week?` ? Or not? – jezrael Mar 30 '19 at 11:47
  • @jezrael his problem is that `''ValueError: Cannot use '%W' or '%U' without day and year'` and the code solve it. – I_Al-thamary Mar 30 '19 at 11:54