-2

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

  • You can use a dataframe or the datetime module. – Cow Sep 13 '22 at 08:37
  • What doesn't work specifically? – SitiSchu Sep 13 '22 at 09:16
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 13 '22 at 09:57
  • I have re-arranged, I want to convert 2018-16 value in attached file to date format instead of object in Python. for example; 2018= year , 16 = week 16 of the year. – Mustafa Polat Sep 13 '22 at 10:15

1 Answers1

0

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
Алексей Р
  • 7,507
  • 2
  • 7
  • 18