0

how can I convert a lot of data in a dataframe from an integer to a datetime? But I only have Year and Week data like the example. The column is named 'Year_Week' and should be tranformed complete.

for example:
Year_Week
201601
201602
201603
...
201652

so ist should be converted like this:

201601 = 2016-01-01
201602 = 2016-01-08

My data is integer, so I converted it to object.

df.Year_Week = df.Year_Week.astype(str)

And then I tried

dateString = df['Year_Week']
dateObject = datetime.datetime.strptime(dateString + '-1', "%Y%W-%w")
print(dateObject)

But there is a TypeError: strptime() argument 1 must be str, not Series

Do not know how to fix it, because I tried to convert it from integer to string, but it became an object... Now i don't know where my fault is

Thank you for help

Hanna
  • 87
  • 6

1 Answers1

1

datetime.datetime.strptime(dateString + '-1', "%Y%W-%w") parameter only looks at one string object. To convert whole series into datetime, you need to do something like this:

pd.to_datetime(df['Year_Week']+ '-1',format="%Y%W-%w")
  • hmm I tried it, but that does not change something in my case – Hanna May 27 '20 at 10:45
  • The command given only **displays** the changed content. Another detail is that explicit conversion to *string* is required. To sum up, run *df['Date'] = pd.to_datetime(df.Year_Week.astype(str) + '-1',format="%Y%W-%w")* – Valdi_Bo May 27 '20 at 11:02