Return Number of Week of datetime Object in Python (Example Code)
In this tutorial, you’ll learn how to get the week number of a datetime object in Python programming.
Example Data
First, we have to load the datetime module, as you can see below:
import datetime # Import datetime |
import datetime # Import datetime
Example: Return the Week Number of datetime
Next, we create a new datetime object as a basis for the example.
date_x = datetime.datetime(2020, 9, 12, 7, 35, 18) # Example date print(date_x) # Print date # 2020-09-12 07:35:18 |
date_x = datetime.datetime(2020, 9, 12, 7, 35, 18) # Example date print(date_x) # Print date # 2020-09-12 07:35:18
Since the isocalendar function works with a tuple containing year, week number, and day of week, we structure our datetime object the same way and can afterwards define the index position we want to be returned:
yr, wn, wd = date_x.isocalendar() # Using isocalendar function print(wn) # Printing number of week # 37 |
yr, wn, wd = date_x.isocalendar() # Using isocalendar function print(wn) # Printing number of week # 37
In our case, we want to know the week number, so we simply print ‘wn’.
Further Resources
You may find some related Python programming tutorials on topics such as data objects, numeric values, and groups below:
- Get N Hours, Minutes & Seconds Earlier as datetime Object in Python
- Get Number of Cases by Group in pandas DataFrame in Python
- All Python Programming Tutorials
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.