What is the date.isocalendar() in Python?

Overview

The isocalendar() function returns a named tuple containing year, week number, and weekday in ISOInternational Organization for Standardization format.

ISO format

  • The ISO year always starts from Monday because Thursday is considered the middle of the week as per the ISO standard 8601.
  • ISO years may consist of either 53 or 54 complete weeks.
  • ISO years do not contain any fractional weeks at the start and end of the year.

Syntax


python isocalendar()

Parameter

It does not take any argument value.

Return value

  • tuple: This method will return the tuple containing year, and week number, day of the week in ISO format.

Code

In the code below, we will fetch today’s date and then map it into the ISO standard time notation:

# Import the date module from datetime
from datetime import date
# Call the today() method that returns today's date
today = date.today()
# Print today's date
print("Today's date=", today)
# Call the isocalendar() method over today variable
# to get its ISO Year, Week Number and Weekday
print('ISO notation: (Year, Week Number, Week Day)=', today.isocalendar())

Explanation

The code above will convert Gregorian date to ISO date formate.

  • Line 4: date.today() returns the current date in today variable.
  • Line 6: On this line, print("Today's date=", today) prints today’s date on console.
  • Line 9: Calls the isocalendar() method to convert today date to ISO formate and prints the results on the console.

Code

# Import date module from datetime
from datetime import date
# make demo date variable
_date = date(2019, 9, 22)
# Call the isocalendar() method over the above-mentioned defined date
ISO_date = _date.isocalendar()
#Print real date and its ISO Year, Week Number, and Weekday
print("The original date is:",_date)
print("Date by using isocalendar method is:", ISO_date)

Explanation

The code below shows the isocalender() method that converts user-defined Date to ISO format.

  • Line 4: Declares and defines the _date variable to specified date i.e., date(2019, 9, 22).
  • Line 6: Converts Gregorian date to ISO format using isocalender() method.
  • Line 8: It prints value in _date variable.
  • Line 9: It prints value in ISO_date variable.

Free Resources