I have data that has date column in this format 'Mar Wk 4 2022'
, where Mar signifies the month that is 'March', 'Wk 4' signifies the week of the month (values ranging from 1 to 5) and '2022' signifies the year,
is there a way to get week start date (Monday) of that week, i.e.,. 4th week of March, 2022?
CodePudding user response:
You can add ' Mon'
(for Monday) to your strings, and convert using pandas.to_datetime
with the %b Wk %U %Y %a
format:
df['start_date'] = pd.to_datetime(df['date'] ' Mon', format='%b Wk %U %Y %a')
output:
date start_date
0 Mar Wk 4 2022 2022-01-24
used input:
df = pd.DataFrame({'date': ['Mar Wk 4 2022']})
CodePudding user response:
If 'week' of the month is:
week 1: 1st - 7th
week 2: 8th - 14th
etc.
it'll depend purely on the day of the 1st of the month so if it's 'Monday', the result will be week * 7 - 6. If it's Tuesday, it'll be 'week * 7', Wednesday will be 'week * 7 - 1' etc.
I don't know numpy, but assume you can get the day as 'Tue' etc. given a day, month and year. So, with appropriate variables the answer is...
monday = week * 7 - ["Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon"].index(day)