I have the following data:
Year&Week | Year | Week |
---|---|---|
2022-50 | 2022 | 50 |
2022-51 | 2022 | 51 |
2022-52 | 2022 | 52 |
I would like to convert that information by adding a new column that reflects the last day (sunday) and the initial day (monday) of the weeks. So my final dataframe should looks like the following:
Year&Week | Year | Week | Initial day of week | Last day of week |
---|---|---|---|---|
2022-50 | 2022 | 50 | 12/Dec/2022 | 18/Dec/2022 |
2022-51 | 2022 | 51 | 19/Dec/2022 | 25/Dec/2022 |
2022-52 | 2022 | 52 | 26/Dec/2022 | 01/Jan/2023 |
CodePudding user response:
We can use pd.to_datetime
and create date
base:
%W
: The week number of the year%Y
: The year number%a
: Weekday, short version%b
: The first three characters of the month name%d
: The day of the month
df['Initial day of week'] = pd.to_datetime(
df['Week'].astype(str) df['Year'].astype(str) 'Mon', format='%W%Y%a'
).dt.strftime("%d/%b/%Y")
df['Last day of week'] = pd.to_datetime(
df['Week'].astype(str) df['Year'].astype(str) 'Sun', format='%W%Y%a'
).dt.strftime("%d/%b/%Y")
print(df)
Output:
Year&Week Year Week Initial day of week Last day of week
0 2022-50 2022 50 12/Dec/2022 18/Dec/2022
1 2022-51 2022 51 19/Dec/2022 25/Dec/2022
2 2022-52 2022 52 26/Dec/2022 01/Jan/2023
CodePudding user response:
You can use the python datetime
module to convert 2022-50
which is probably is in the "%Y%W" Format to M/d/y
format, like the below's peace of codes:
from datetime import datetime
input_date = "2022-50"
right_date = datetime.strptime(input_date, "%Y-%W")
formate_date_reult = right_date.strftime("%m/%d/%Y")
print(formate_date_reult) # Output is: 12/25/2022