Adam Roman
Adam Roman

Reputation: 97

Pandas convert two separate columns into a single datetime column?

I have two columns in a pandas dataframe that I want to convert into a single datetime column. The problem is that one of the columns is the week of the year and one is the actual year. It looks something like this:

WEEK_OF_YEAR | YEAR
1              2016
2              2016  
...
52             2016
1              2017
2              2017
3              2017
...
52             2017
1              2018

How can I make another column called "DATE" that is the datetime conversion of both columns together?

Upvotes: 1

Views: 119

Answers (2)

jezrael
jezrael

Reputation: 862581

If converting week of year is necesary define day of week by %w:

%w - Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

#for Sundays is set value to 0
s = df['WEEK_OF_YEAR'].astype(str)  + '-0-' + df['YEAR'].astype(str)
df['date'] = pd.to_datetime(s, format='%W-%w-%Y')
print (df)
   WEEK_OF_YEAR  YEAR       date
0             1  2016 2016-01-10
1             2  2016 2016-01-17
2            52  2016 2017-01-01
3             1  2017 2017-01-08
4             2  2017 2017-01-15
5             3  2017 2017-01-22
6            52  2017 2017-12-31
7             1  2018 2018-01-07

Upvotes: 3

Zmnako Awrahman
Zmnako Awrahman

Reputation: 548

Try this:

import time

df.DATE = time.asctime(time.strptime('{} {} 1'.format(df.YEAR, df.WEEK_OF_YEAR), '%Y %W %w'))

Upvotes: 0

Related Questions