Search code examples
pythonpandasstrftimestring-to-datetime

Converting a string containing year and week number to datetime in Pandas


I have a column in a Pandas dataframe that contains the year and the week number (1 up to 52) in one string in this format: '2017_03' (meaning 3d week of year 2017).

I want to convert the column to datetime and I am using the pd.to_datetime() function. However I get an exception:

pd.to_datetime('2017_01',format = '%Y_%W')
ValueError: Cannot use '%W' or '%U' without day and year

On the other hand the strftime documentation mentions that:

enter image description here

I am not sure what I am doing wrong.


Solution

  • You need also define start day:

    a = pd.to_datetime('2017_01_0',format = '%Y_%W_%w')
    print (a)
    2017-01-08 00:00:00
    
    a = pd.to_datetime('2017_01_1',format = '%Y_%W_%w')
    print (a)
    2017-01-02 00:00:00
    
    a = pd.to_datetime('2017_01_2',format = '%Y_%W_%w')
    print (a)
    2017-01-03 00:00:00