Get Week Number of datetime in Python (Example)
In this Python tutorial, you’ll learn how to return the number of a week from a datetime object.
Table of contents:
Let’s do this…
Example Data & Add-On Libraries
First, we have to import the datetime module:
import datetime # Import datetime module to Python
Furthermore, have a look at the following example data:
my_date = datetime.datetime(2022, 3, 9, 12, 16, 45) # Creating example data print(my_date) # Show example date # 2022-03-09 12:16:45
We will use the above datetime object for this tutorial.
Example: Get Week Number of datetime Object
In this section, I’ll explain how to return the number of week from our example date.
To achieve this, we use the isocalendar function, which would return us a tuple indexed with year, week number, and weekday.
So in our case, since we want to know only the number of the week, we add to the isocalendar function the index:
week_number = my_date.isocalendar() # Applying isocalendar function print(week_number) # Show week number # 10
As you can see on the output above, our example datetime object belongs to the week number 10.
So in case you want to return the weekday number, just set the index to , or to  if you want to show the year… Give it a try!
Video, Further Resources & Summary
Do you need more explanations on the Python programming syntax of this article? Then you may have a look at the following video instruction on my YouTube channel. In the video, I’m explaining the Python code of this tutorial in the Python programming language.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition to the video, you may have a look at some other articles on this homepage:
- Add & Subtract Weeks to & from Date in Python (2 Examples)
- Get Current Day of Week in Python – Number & Name (3 Examples)
- Calculate Time Difference Between Two datetime Objects in Python (Example)
- Python Programming Tutorials
You have learned in this tutorial how to get the week number of a datetime object in the Python programming language. Please let me know in the comments section, in case you have further questions and/or comments.
This page was created in collaboration with Matthias Bäuerlen. Have a look at Matthias’ author page to get more information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.