Convert Weeknumber to date using Python and Pandas

86 views Asked by At

I need help extracting the weekdate from my df:

df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

my desired output is to have a new column named "weekDate" which will pull the date of the first Monday of the specific week in a "yyyy-MM-dd" format:

E.g. for Week: 12, Year: 2023 ====> "2023-03-20" (which is the first Monday of week 12 in 2023)

Many thanks in advance,

2

There are 2 answers

0
mozway On

You can concatenate the columns and use to_datetime with the '%Y-%W-%w' format (more info here):

df['weekDate'] = pd.to_datetime(
               df['year'].astype(str)+'-'+df['weeknum'].astype(str)+'-1',
               format='%Y-%W-%w')            #                        ^
                                             #          1 is for Monday
# or                                         #                   |
df['weekDate'] = pd.to_datetime(             #                   v
               df['year'].astype(str)+df['weeknum'].astype(str)+'1',
               format='%Y%W%w')

Output:

   weeknum  year   weekDate
0       12  2023 2023-03-20
1       24  2023 2023-06-12
2       36  2023 2023-09-04
3       48  2023 2023-11-27
4       50  2023 2023-12-11
2
Sharim09 On

To convert week numbers to dates, you can use the datetime module with the pandas library.

import pandas as pd
from datetime import datetime, timedelta


df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

# Function to get the date of the first Monday of a given week and year
def get_first_monday(year, week):
    date_str = f'{year}-W{week}'
    date_obj = datetime.strptime(date_str + '-1', "%Y-W%W-%w")
    return date_obj.strftime('%Y-%m-%d')

# Apply the function to create the 'weekDate' column
df['weekDate'] = df.apply(lambda row: get_first_monday(row['year'], row['weeknum']), axis=1)

print(df)

Output

   weeknum  year    weekDate
0       12  2023  2023-03-20
1       24  2023  2023-06-12
2       36  2023  2023-09-04
3       48  2023  2023-11-27
4       50  2023  2023-12-11