Python datetime isocalendar() Method with Example

Python datetime.isocalendar() Method: In this tutorial, we will learn about the isocalendar() method of datetime class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python datetime.isocalendar() Method

The datetime.isocalendar() method is used to get an ISO Calendar, it uses a datetime class object and returns a 3-tuple (ISO year, ISO week number, ISO weekday).

Most of the date and time calendar follow the Gregorian calendar. The ISO calendar is a widely used variant of the Gregorian one. The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.
For example, 2004 begins on a Thursday, so the first week of ISO year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004:

Weekday number for Monday is 1 while incrementing by 1 for the coming days.

Module

The following module is required to use isocalendar() method:

import datetime

Class

The following class is required to use isocalendar() method:

from datetime import datetime

Syntax

The following is the syntax of isocalendar() method:

isocalendar()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is a tuple which tells us what is the ISO year, ISO week and the ISO weekday of that date.

Example of isocalendar() Method in Python

## importing datetime class
from datetime import datetime

## Creating an instance
x = datetime.now()
d = x.isocalendar()
print("Original date:",x)
print("Today's date in isocalendar is:", d)
print()

x = datetime(2004, 10, 30, 12, 12, 12)
d = x.isocalendar()
## this returns a date object, extracted from 
## the datetime object
dd = x.date()
print("Date", str(dd) ,"in isocalendar is:", d)
print()

x = datetime(2020, 10, 27, 10, 3, 33)
d = x.isocalendar()
dd = x.date()
print("Original date was:",str(dd))
print("ISO year:",d[0],"ISO week:",d[1],"ISO weekday:",d[2])

Output

Original date: 2020-05-01 22:40:19.039474
Today's date in isocalendar is: (2020, 18, 5)

Date 2004-10-30 in isocalendar is: (2004, 44, 6)

Original date was: 2020-10-27
ISO year: 2020 ISO week: 44 ISO weekday: 2



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.