-3

I have a data frame in python.i need to change its data type from string object to datetime object. I need to forecast for next year,for that the data type should be in datetime. week number goes upto (2015-52)

WeekKey SalesVolume

0 2015-02 444

1 2015-03 1451

2 2015-04 2556

3 2015-05 3762

4 2015-06 4883

current data type is as follows.

Data columns (total 2 columns):

0 WeekKey 60 non-null object

1 SalesVolume 60 non-null int64

dtypes: int64(1), object(1)

I tried

df_data['WeekKey'] = pd.to_datetime(df_data['WeekKey'], format='%Y-%W')

but getting an error.

TypeError: Unrecognized value type: <class 'str'>

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

Please help me to sort this out.

athulya
  • 1
  • 1
  • 2
    Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See also: [ask]. Also please provide some sample data (See [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)). – RoseGod Dec 23 '21 at 12:33
  • Does this answer your question? [Convert DataFrame column type from string to datetime](https://stackoverflow.com/questions/17134716/convert-dataframe-column-type-from-string-to-datetime) – 3dSpatialUser Dec 23 '21 at 12:35
  • http://strftime.org/ is your friend – MattDMo Dec 23 '21 at 12:39

1 Answers1

0

You can create dedicated namedtuple:

from collections import namedtuple

year_week_item = "201532"
YearWeek = namedtuple('YearWeek', ['year', 'week'])
year_week = YearWeek(year_week_item[:4], year_week_item[4:])
print(year_week)

Output:

YearWeek(year='2015', week='32')

Or you can parse it to datetime: Get date from week number

David Meu
  • 1,527
  • 9
  • 14