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[0], week number[1], and weekday[2].

So in our case, since we want to know only the number of the week, we add to the isocalendar function the index[1]:

week_number = my_date.isocalendar()[1]               # 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 [2], or to [0] 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.

 

The YouTube video will be added soon.

 

In addition to the video, you may have a look at some other articles on this homepage:

 

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.

 

Matthias Bäuerlen Python Programmer

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top