Return Start & End of Week Based on datetime Object in Python (2 Examples)
This post shows how to extract the start/end of a week based on a datetime object in the Python programming language.
Creation of Example Data
Before we can start, we have to import the following modules:
from datetime import datetime, timedelta # Load datetime and timedelta
As a basement for the tutorial, we will use the example date below:
x = '23/06/2021' # Constructing example data print(x) # 23/06/2021
Example 1: Start of Week from Any Date
We will use the functions of the datetime module, which we have imported at the beginning. To do so, we convert our example date to a datetime object:
dt_x = datetime.strptime(x,'%d/%m/%Y') # strptime() function print(dt_x) # 2021-06-23 00:00:00
Now, we are able to apply the timedelta function in combination with the weekday function to get the start date of the week:
week_start_time = dt_x - timedelta(days = dt_x.weekday()) # timedelta() & weekday() print(week_start_time) # Show week start # 2021-06-21 00:00:00
To have a clear structure, we remove the unnecessary time components afterwards:
week_start_no_time = week_start_time.strftime('%d/%m/%Y') # Remove time component print(week_start_no_time) # 21/06/2021
Week starts on Monday 21/06/2021…
Example 2: End of Week from Any Date
From the week start, we simply get to the end of the week by adding a timedelta of 6 days:
week_end_time = week_start_time + timedelta(days=6) # timedelta function print(week_end_time) # Show End of Week # 2021-06-27 00:00:00
And also remove the redundant time component:
week_end_no_time = week_end_time.strftime('%d/%m/%Y') # Remove time component print(week_end_no_time) # 27/06/2021
End of the week is Sunday 27/06/2021.
Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.