Convert arbitrary date to the date of Monday or Sundy within the same week in Python


It is common practice to convert date to the week number for normalization or feature preprocessing. While this is pretty useful, sometimes we want to compare the week number in a more strict fashion, such that we can order week 50 of last year and week 2 of this year, for example.

Following code shows both
(1) how to get week number of datetime object
(2) get the exacte date of the Monday or Sunday within the same week

get week number for any date

from datetime import timedelta, datetime

# example of a date str
dt_str = '2022/02/22 05:23:20'

# convert string to datetime object
dt_obj = datetime.strptime(dt_str, '%Y/%m/%d %H:%M:%S')

# get date of that Monday
year, week_num, day_of_week = dt_obj.isocalendar()
print(week_num)




8

get date of Monday or Sunday for any date within the same week

from datetime import timedelta, datetime

# get the date of Monday for that week
def start_date_of_week(date):
start = date - timedelta(days=date.weekday())

return str(start)[:10]

# get the date of Sunday for that week
def end_date_of_week(date):
start = date - timedelta(days=date.weekday())
end = start + timedelta(days=6)
return str(end)[:10]



# example of a date str
dt_str = '2022/02/22 05:23:20'

# convert string to datetime object
dt_obj = datetime.strptime(dt_str, '%Y/%m/%d %H:%M:%S')

# get date of that Monday
print(start_date_of_week(dt_obj) )


# get date of that Sunday
print(end_date_of_week(dt_obj) )
2022-02-21
2022-02-27

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC