How to convert year and week to date type?

Viewed 47

I load the attached excel file into python, but it does not detect the values in the cell in date format.

It treats cell values as Object.

How can I convert the year and week in the attached file (eg 2018(year)-16(week) to date type for use in python?

I used the code below but it is not working.

import datetime

def to_datetime(x):
  return datetime.datetime.strptime(x + '-1', "%Y-%W-%w")

train['date'] = train['date'].apply(to_datetime)

enter image description here

1 Answers

Based on https://stackoverflow.com/a/17087427/15035314

import pandas as pd
train = pd.DataFrame({'date': [f'2018-{i}' for i in range(16, 25)]})
train['date'] = pd.to_datetime(train['date']+'-1', format='%Y-%W-%w',errors='coerce')
print(train)
        date
0 2018-04-16
1 2018-04-23
2 2018-04-30
3 2018-05-07
4 2018-05-14
5 2018-05-21
6 2018-05-28
7 2018-06-04
8 2018-06-11
Related