Course Title: Programming in Python
Course Code: BTAIML501- 20
Module 5:
Generators in Python
A Generator in Python is a function that returns an iterator using the Yield
keyword. In this article, we will discuss how the generator function works in
Python.
Generator Function in Python
A generator function in Python is defined like a normal function, but whenever
it needs to generate a value, it does so with the yield keyword rather than return.
If the body of a def contains yield, the function automatically becomes a Python
generator function.
Create a Generator in Python
In Python, we can create a generator function by simply using the def keyword
and the yield keyword. The generator has the following syntax in Python:
def function_name():
yield statement
Example:
In this example, we will create a simple generator that will yield three integers.
Then we will print these integers by using Python for loop.
Python
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)
Output:
1
2
3
Generator Object
Python Generator functions return a generator object that is iterable, i.e., can be
used as an Iterator. Generator objects are used either by calling the next method
of the generator object or using the generator object in a “for in” loop.
Example:
In this example, we will create a simple generator function in Python to
generate objects using the next() function.
Python
# A Python program to demonstrate use of
# generator object with next()
# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# x is a generator object
x = simpleGeneratorFun()
# Iterating over the generator object using next
# In Python 3, __next__()
print(next(x))
print(next(x))
print(next(x))
Output:
1
2
3
Example:
In this example, we will create two generators for Fibonacci Numbers, first a
simple generator and second generator using a for loop.
Python
def fib(limit):
a, b = 0, 1
while b < limit:
yield b
a, b = b, a + b
# Create a generator object
x = fib(200)
# Iterate over the generator object and print each value
for i in x:
print(i)
Output
1
1
2
3
5
8
13
21
34
55
89
144
Python Generator Expression
In Python, generator expression is another way of writing the generator
function. It uses the Python list comprehension technique but instead of storing
the elements in a list in memory, it creates generator objects.
Generator Expression Syntax
The generator expression in Python has the following Syntax:
(expression for item in iterable)
Example:
In this example, we will create a generator object that will print the multiples of
5 between the range of 0 to 5 which are also divisible by 2.
Python
# generator expression
generator_exp = (i * 5 for i in range(5) if i%2==0)
for i in generator_exp:
print(i)
Output:
0
10
20
Applications of Generators in Python
Suppose we create a stream of Fibonacci numbers, adopting the generator
approach makes it trivial; we just have to call next(x) to get the next Fibonacci
number without bothering about where or when the stream of numbers ends. A
more practical type of stream processing is handling large data files such as log
files. Generators provide a space-efficient method for such data processing as
only parts of the file are handled at one given point in time. We can also use
Iterators for these purposes, but Generator provides a quick way (We don’t need
to write __next__ and __iter__ methods here).
Iterators in Python
An iterator in Python is an object that is used to iterate over iterable objects like
lists, tuples, dicts, and sets. The Python iterators object is initialized using
the iter() method. It uses the next() method for iteration.
1. __iter__(): The iter() method is called for the initialization of an iterator.
This returns an iterator object
2. __next__(): The next method returns the next value for the iterable.
When we use a for loop to traverse any iterable object, internally it uses
the iter() method to get an iterator object, which further uses the next()
method to iterate over. This method raises a StopIteration to signal the
end of the iteration.
Python iter() Example
Python3
string = "GFG"
ch_iterator = iter(string)
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
Output :
G
F
G
Creating and looping over an iterator using iter() and next()
Below is a simple Python Iterator that creates an iterator type that iterates from
10 to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14
15. And if the limit is 5, then it prints nothing.
Python3
# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
# Constructor
def __init__(self, limit):
self.limit = limit
# Creates iterator object
# Called when iteration is initialized
def __iter__(self):
self.x = 10
return self
# To move to next element. In Python 3,
# we should replace next with __next__
def __next__(self):
# Store current value ofx
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
raise StopIteration
# Else increment and return old value
self.x = x + 1;
return x
# Prints numbers from 10 to 15
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)
Output:
10
11
12
13
14
15
Iterating over built-in iterable using iter() method
In the following iterations, the iteration state and iterator variable is managed
internally (we can’t see it) using an iterator object to traverse over the built-in
iterable like list, tuple, dict, etc.
Python3
# Sample built-in iterators
# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Output:
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
Iterable vs Iterator
Python iterable and Python iterator are different. The main difference between
them is, iterable in Python cannot save the state of the iteration, whereas in
iterators the state of the current iteration gets saved.
Note: Every iterator is also an iterable, but not every iterable is an iterator
in Python.
Read more – Difference between iterable and iterator.
Iterating on an Iterable
Iterating on each item of the iterable.
Python3
tup = ('a', 'b', 'c', 'd', 'e')
for item in tup:
print(item)
Output:
a
b
c
d
e
Iterating on an iterator
Python3
tup = ('a', 'b', 'c', 'd', 'e')
# creating an iterator from the tuple
tup_iter = iter(tup)
print("Inside loop:")
# iterating on each item of the iterator object
for index, item in enumerate(tup_iter):
print(item)
# break outside loop after iterating on 3
elements
if index == 2:
break
# we can print the remaining items to be
iterated using next()
# thus, the state was saved
print("Outside loop:")
print(next(tup_iter))
print(next(tup_iter))
Output:
Inside loop:
a
b
c
Outside loop:
d
e
Getting StopIteration Error while using iterator
Iterable in Python can be iterated over multiple times, but iterators raise
StopIteration Error when all items are already iterated.
Here, we are trying to get the next element from the iterator after the completion
of the for-loop. Since the iterator is already exhausted, it raises a StopIteration
Exception. Whereas, using an iterable, we can iterate on multiple times using
for loop or can get items using indexing.
Python3
iterable = (1, 2, 3, 4)
iterator_obj = iter(iterable)
print("Iterable loop 1:")
# iterating on iterable
for item in iterable:
print(item, end=",")
print("\nIterable Loop 2:")
for item in iterable:
print(item, end=",")
print("\nIterating on an iterator:")
# iterating on an iterator object multiple times
for item in iterator_obj:
print(item, end=",")
print("\nIterator: Outside loop")
# this line will raise StopIteration Exception
# since all items are iterated in the previous
for-loop
print(next(iterator_obj))
Output:
Iterable loop 1:
1,2,3,4,
Iterable Loop 2:
1,2,3,4,
Iterating on an iterator:
1,2,3,4,
Iterator: Outside loop
Traceback (most recent call last):
File "scratch_1.py", line 21, in <module>
print(next(iterator_obj))
StopIteration
Table of difference between Iterator vs Generators
Iterator Generator
Function is used to
Class is used to implement an iterator implement a
generator.
All the local
Local Variables aren’t used variables before the
here. yield function are
stored.
Generators are
mostly used in
loops to generate an
Iterators are used mostly to iterate or convert other
iterator by returning
objects to an iterator using iter()
all the values in the
function.
loop without
affecting the
iteration of the loop
Iterator Generator
Generator uses yield
Iterator uses iter() and next() functions
keyword
Every generator is
Every iterator is not a generator
an iterator
Python Collections Module
The collection Module in Python provides different types of containers. A
Container is an object that is used to store different objects and provide a way to
access the contained objects and iterate over them. Some of the built-in
containers are Tuple, List, Dictionary, etc. In this article, we will discuss the
different containers provided by the collections module.
Table of Content:
Counters
OrderedDict
DefaultDict
ChainMap
NamedTuple
DeQue
UserDict
UserList
UserString
Counters
A counter is a sub-class of the dictionary. It is used to keep the count of the
elements in an iterable in the form of an unordered dictionary where the key
represents the element in the iterable and value represents the count of that
element in the iterable.
Note: It is equivalent to bag or multiset of other languages.
Syntax:
class collections.Counter([iterable-or-mapping])
Initializing Counter Objects
The counter object can be initialized using the counter() function and this
function can be called in one of the following ways:
With a sequence of items
With a dictionary containing keys and counts
With keyword arguments mapping string names to counts
Example:
Python
# A Python program to show different
# ways to create Counter
from collections import Counter
# With sequence of items
print(Counter(['B','B','A','B','C','A','B',
'B','A','C']))
# with dictionary
print(Counter({'A':3, 'B':5, 'C':2}))
# with keyword arguments
print(Counter(A=3, B=5, C=2))
Output:
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Note: For more information, refer Counters in Python.
OrderedDict
An OrderedDict is also a sub-class of dictionary but unlike dictionary, it
remembers the order in which the keys were inserted.
Syntax:
class collections.OrderDict()
Example:
Python
# A Python program to demonstrate working
# of OrderedDict
from collections import OrderedDict
print("This is a Dict:\n")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
for key, value in d.items():
print(key, value)
print("\nThis is an Ordered Dict:\n")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
Output:
This is a Dict:
a1
b2
c3
d4
This is an Ordered Dict:
a1
b2
c3
d4
While deleting and re-inserting the same key will push the key to the last to
maintain the order of insertion of the key.
Example:
Python
# A Python program to demonstrate working
# of OrderedDict
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print('Before Deleting')
for key, value in od.items():
print(key, value)
# deleting element
od.pop('a')
# Re-inserting the same
od['a'] = 1
print('\nAfter re-inserting')
for key, value in od.items():
print(key, value)
Output:
Before Deleting
a1
b2
c3
d4
After re-inserting
b2
c3
d4
a1
Note: for more information, refer OrderedDict in Python
DefaultDict
A DefaultDict is also a sub-class to dictionary. It is used to provide some default
values for the key that does not exist and never raises a KeyError.
Syntax:
class collections.defaultdict(default_factory)
default_factory is a function that provides the default value for the dictionary
created. If this parameter is absent then the KeyError is raised.
Initializing DefaultDict Objects
DefaultDict objects can be initialized using DefaultDict() method by passing the
data type as an argument.
Example:
Python
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining the dict
d = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
# Iterate through the list
# for keeping the count
for i in L:
# The default value is 0
# so there is no need to
# enter the key first
d[i] += 1
print(d)
Output:
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
Example 2:
Python
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining a dict
d = defaultdict(list)
for i in range(5):
d[i].append(i)
print("Dictionary with values as list:")
print(d)
Output:
Dictionary with values as list:
defaultdict(<class ‘list’>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
Note: For more information, refer Defaultdict in Python
ChainMap
A ChainMap encapsulates many dictionaries into a single unit and returns a list
of dictionaries.
Syntax:
class collections.ChainMap(dict1, dict2)
Example:
Python
# Python program to demonstrate
# ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
print(c)
Output:
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
Accessing Keys and Values from ChainMap
Values from ChainMap can be accessed using the key name. They can also be
accessed by using the keys() and values() method.
Example:
Python
# Python program to demonstrate
# ChainMap
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
# Defining the chainmap
c = ChainMap(d1, d2, d3)
# Accessing Values using key name
print(c['a'])
# Accessing values using values()
# method
print(c.values())
# Accessing keys using keys()
# method
print(c.keys())
Output:
1
ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))
Adding new dictionary
A new dictionary can be added by using the new_child() method. The newly
added dictionary is added at the beginning of the ChainMap.
Example:
Python
# Python code to demonstrate ChainMap and
# new_child()
import collections
# initializing dictionaries
dic1 = { 'a' : 1, 'b' : 2 }
dic2 = { 'b' : 3, 'c' : 4 }
dic3 = { 'f' : 5 }
# initializing ChainMap
chain = collections.ChainMap(dic1, dic2)
# printing chainMap
print ("All the ChainMap contents are : ")
print (chain)
# using new_child() to add new dictionary
chain1 = chain.new_child(dic3)
# printing chainMap
print ("Displaying new ChainMap : ")
print (chain1)
Output:
All the ChainMap contents are :
ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Displaying new ChainMap :
ChainMap({'f': 5}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Note: For more information, refer ChainMap in Python
NamedTuple
A NamedTuple returns a tuple object with names for each position which the
ordinary tuples lack. For example, consider a tuple names student where the
first element represents fname, second represents lname and the third element
represents the DOB. Suppose for calling fname instead of remembering the
index position you can actually call the element by using the fname argument,
then it will be really easy for accessing tuples element. This functionality is
provided by the NamedTuple.
Syntax:
class collections.namedtuple(typename, field_names)
Example:
Python
# Python code to demonstrate namedtuple()
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# Access using index
print ("The Student age using index is : ",end ="")
print (S[1])
# Access using name
print ("The Student name using keyname is : ",end ="")
print (S.name)
Output:
The Student age using index is : 19
The Student name using keyname is : Nandini
Conversion Operations
1. _make(): This function is used to return a namedtuple() from the iterable
passed as argument.
2. _asdict(): This function returns the OrdereDict() as constructed from the
mapped values of namedtuple().
Example:
Python
# Python code to demonstrate namedtuple() and
# _make(), _asdict()
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
# Adding values
S = Student('Nandini','19','2541997')
# initializing iterable
li = ['Manjeet', '19', '411997' ]
# initializing dict
di = { 'name' : "Nikhil", 'age' : 19 , 'DOB' : '1391997' }
# using _make() to return namedtuple()
print ("The namedtuple instance using iterable is : ")
print (Student._make(li))
# using _asdict() to return an OrderedDict()
print ("The OrderedDict instance using namedtuple is : ")
print (S._asdict())
Output:
The namedtuple instance using iterable is :
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is :
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])
Note: For more information, refer NamedTuple in Python
Deque
Deque (Doubly Ended Queue) is the optimized list for quicker append and pop
operations from both sides of the container. It provides O(1) time complexity
for append and pop operations as compared to list with O(n) time complexity.
Syntax:
class collections.deque(list)
This function takes the list as an argument.
Example:
Python
# Python code to demonstrate deque
from collections import deque
# Declaring deque
queue = deque(['name','age','DOB'])
print(queue)
Output:
deque(['name', 'age', 'DOB'])
Inserting Elements
Elements in deque can be inserted from both ends. To insert the elements from
right append() method is used and to insert the elements from the left
appendleft() method is used.
Example:
Python
# Python code to demonstrate working of
# append(), appendleft()
from collections import deque
# initializing deque
de = deque([1,2,3])
# using append() to insert element at right end
# inserts 4 at the end of deque
de.append(4)
# printing modified deque
print ("The deque after appending at right is : ")
print (de)
# using appendleft() to insert element at right end
# inserts 6 at the beginning of deque
de.appendleft(6)
# printing modified deque
print ("The deque after appending at left is : ")
print (de)
Output:
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
Removing Elements
Elements can also be removed from the deque from both the ends. To remove
elements from right use pop() method and to remove elements from the left use
popleft() method.
Example:
Python
# Python code to demonstrate working of
# pop(), and popleft()
from collections import deque
# initializing deque
de = deque([6, 1, 2, 3, 4])
# using pop() to delete element from right end
# deletes 4 from the right end of deque
de.pop()
# printing modified deque
print ("The deque after deleting from right is : ")
print (de)
# using popleft() to delete element from left end
# deletes 6 from the left end of deque
de.popleft()
# printing modified deque
print ("The deque after deleting from left is : ")
print (de)
Output:
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
Note: For more information, refer Deque in Python.
UserDict
UserDict is a dictionary-like container that acts as a wrapper around the
dictionary objects. This container is used when someone wants to create their
own dictionary with some modified or new functionality.
Syntax:
class collections.UserDict([initialdata])
Example:
Python
# Python program to demonstrate
# userdict
from collections import UserDict
# Creating a Dictionary where
# deletion is not allowed
class MyDict(UserDict):
# Function to stop deletion
# from dictionary
def __del__(self):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# dictionary
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop popitem
# from Dictionary
def popitem(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
d = MyDict({'a':1,
'b': 2,
'c': 3})
d.pop(1)
Output:
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 32, in <module>
d.pop(1)
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 20, in pop
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Exception ignored in: <bound method MyDict.__del__ of {'a': 1, 'b': 2, 'c': 3}>
Traceback (most recent call last):
File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 15, in __del__
RuntimeError: Deletion not allowed
Note: For more information, refer UserDict in Python
UserList
UserList is a list like container that acts as a wrapper around the list objects.
This is useful when someone wants to create their own list with some modified
or additional functionality.
Syntax:
class collections.UserList([list])
Example:
Python
# Python program to demonstrate
# userlist
from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
# Function to stop deletion
# from List
def remove(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# List
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
L = MyList([1, 2, 3, 4])
print("Original List")
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
# Deleting From List
L.remove()
Output:
Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
File "/home/c90487eefa7474c0566435269f50a52a.py", line 33, in <module>
L.remove()
File "/home/c90487eefa7474c0566435269f50a52a.py", line 15, in remove
raise RuntimeError("Deletion not allowed")
RuntimeError: Deletion not allowed
Note: For more information, refer UserList in Python
UserString
UserString is a string like container and just like UserDict and UserList it acts
as a wrapper around string objects. It is used when someone wants to create
their own strings with some modified or additional functionality.
Syntax:
class collections.UserString(seq)
Example:
Python
# Python program to demonstrate
# userstring
from collections import UserString
# Creating a Mutable String
class Mystring(UserString):
# Function to append to
# string
def append(self, s):
self.data += s
# Function to remove from
# string
def remove(self, s):
self.data = self.data.replace(s, "")
# Driver's code
s1 = Mystring("Geeks")
print("Original String:", s1.data)
# Appending to string
s1.append("s")
print("String After Appending:", s1.data)
# Removing from string
s1.remove("e")
print("String after Removing:", s1.data)
Output:
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
Note: For more information, refer UserString in Python
Python Collections Module – FAQs
How to use the Counter class in the collections module?
The Counter class is a specialized dictionary for counting hashable objects. It is
used to count the frequency of elements in an iterable.
Example:
from collections import Counter
# Create a Counter object
c = Counter(['a', 'b', 'c', 'a', 'b', 'a'])
# Output the counts
print(c) # Counter({'a': 3, 'b': 2, 'c': 1})
# Access count of a specific element
print(c['a']) # 3
# Find most common elements
print(c.most_common(2)) # [('a', 3), ('b', 2)]
What is namedtuple and its applications in Python?
namedtuple is a factory function in the collections module that creates tuple
subclasses with named fields. It allows you to access elements using named
attributes instead of numerical indices.
Example:
from collections import namedtuple
# Define a namedtuple class
Person = namedtuple('Person', ['name', 'age'])
# Create an instance of Person
p = Person(name='John', age=30)
# Access elements using attributes
print(p.name) # John
print(p.age) # 30
Applications:
Use namedtuple for data structures where you want to give names to the
elements, making the code more readable.
Useful for representing records or simple data objects.
Python datetime module
Last Updated : 26 Dec, 2023
In Python, date and time are not data types of their own, but a module
named DateTime in Python can be imported to work with the date as well as
time. Python Datetime module comes built into Python, so there is no need to
install it externally.
In this article, we will explore How DateTime in Python works and what are
the main classes of DateTime module in Python.
Table of Content
Python DateTime module
Python Date Class
Python Time class
Python Datetime class
Python Timedelta Class
Python DateTime.tzinfo()
Python DateTime timezone
Python DateTime module
Python Datetime module supplies classes to work with date and time. These
classes provide several functions to deal with dates, times, and time intervals.
Date and DateTime are an object in Python, so when you manipulate them, you
are manipulating objects and not strings or timestamps.
The DateTime module is categorized into 6 main classes –
date – An idealized naive date, assuming the current Gregorian calendar
always was, and always will be, in effect. Its attributes are year, month,
and day. you can refer to – Python DateTime – Date Class
time – An idealized time, independent of any particular day, assuming
that every day has exactly 24*60*60 seconds. Its attributes are hour,
minute, second, microsecond, and tzinfo. You can refer to – Python
DateTime – Time Class
date-time – It is a combination of date and time along with the attributes
year, month, day, hour, minute, second, microsecond, and tzinfo. You can
refer to – Python DateTime – DateTime Class
timedelta – A duration expressing the difference between two date, time,
or datetime instances to microsecond resolution. You can refer to
– Python DateTime – Timedelta Class
tzinfo – It provides time zone information objects. You can refer to
– Python – datetime.tzinfo()
timezone – A class that implements the tzinfo abstract base class as a
fixed offset from the UTC (New in version 3.2). You can refer to
– Handling timezone in Python
Python Date Class
The date class is used to instantiate date objects in Python. When an object of
this class is instantiated, it represents a date in the format YYYY-MM-DD. The
constructor of this class needs three mandatory arguments year, month, and
date.
Python Date class Syntax
class datetime.date(year, month, day)
The arguments must be in the following range –
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
Note – If the argument is not an integer it will raise a TypeError and if it is
outside the range a ValueError will be raised.
Date object representing data in Python
Initializing the constructor and passing arguments in the format year, month,
and date.
Python3
# Python program to
# demonstrate date class
# import the date class
from datetime import date
my_date = date(1996, 12, 11)
print("Date passed as argument is", my_date)
# Uncommenting my_date = date(1996, 12,
39)
# will raise an ValueError as it is
# outside range
# uncommenting my_date = date('1996', 12,
11)
# will raise a TypeError as a string is
# passed instead of integer
Output:
Date passed as argument is 1996-12-11
Traceback (most recent call last):
File "/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py", line 14, in
my_date = date(1996, 12, 39)
ValueError: day is out of range for month
Traceback (most recent call last):
File "/home/53b974e10651f1853eee3c004b48c481.py", line 18, in
my_date = date('1996', 12, 11)
TypeError: an integer is required (got type str)
Get the Current Date
To return the current local date today() function of the date class is used. today()
function comes with several attributes (year, month, and day). These can be
printed individually.
Python3
# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
Output
Today's date is 2021-08-19
Get Today’s Year, Month, and Date
We can get the year, month, and date attributes from the date object using the
year, month and date attribute of the date class.
Python3
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
Output
Current year: 2021
Current month: 8
Current day: 19
Get Date from Timestamp
We can create date objects from timestamps y=using the fromtimestamp()
method. The timestamp is the number of seconds from 1st January 1970 at UTC
to a particular date.
Python3
from datetime import datetime
# Getting Datetime from timestamp
date_time =
datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)
Output
Datetime from timestamp: 2029-10-25 16:17:48
Convert Date to String
We can convert date object to a string representation using two functions
isoformat() and strftime().
Python3
from datetime import date
# calling the today
# function of date class
today = date.today()
# Converting the date to the string
Str = date.isoformat(today)
print("String Representation", Str)
print(type(Str))
Output
String Representation 2021-08-19
<class 'str'>
List of Date Class Methods
Function Name Description
ctime() Return a string representing the date
Returns a date corresponding to the
fromisocalendar()
ISO calendar
Returns a date object from the string
fromisoformat()
representation of the date
Returns a date object from the
fromordinal() proleptic Gregorian ordinal, where
January 1 of year 1 has ordinal 1
Returns a date object from the
fromtimestamp()
POSIX timestamp
Returns a tuple year, week, and
isocalendar()
weekday
Returns the string representation of
isoformat()
the date
Returns the day of the week as an
isoweekday() integer where Monday is 1 and
Sunday is 7
Changes the value of the date object
replace()
with the given parameter
Function Name Description
Returns a string representation of the
strftime()
date with the given format
Returns an object of type
timetuple()
time.struct_time
today() Returns the current local date
Return the proleptic Gregorian
toordinal() ordinal of the date, where January 1
of year 1 has ordinal 1
Returns the day of the week as
weekday() integer where Monday is 0 and
Sunday is 6
Python Time class
The time class creates the time object which represents local time, independent
of any day.
Constructor Syntax:
class datetime.time(hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, *, fold=0)
All the arguments are optional. tzinfo can be None otherwise all the attributes
must be integer in the following range –
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]
Example 1: Time object representing time in Python
Python3
# Python program to
# demonstrate time class
from datetime import time
# calling the constructor
my_time = time(13, 24, 56)
print("Entered time", my_time)
# calling constructor with 1
# argument
my_time = time(minute=12)
print("\nTime with one argument", my_time)
# Calling constructor with
# 0 argument
my_time = time()
print("\nTime without argument", my_time)
# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range
# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int
Output:
Entered time 13:24:56
Time with one argument 00:12:00
Time without argument 00:00:00
Traceback (most recent call last):
File "/home/95ff83138a1b3e67731e57ec6dddef25.py", line 21, in
print(time(hour=26))
ValueError: hour must be in 0..23
Traceback (most recent call last):
File "/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py", line 21, in
print(time(hour='23'))
TypeError: an integer is required (got type str)
Example 2: Get hours, minutes, seconds, and microseconds
After creating a time object, its attributes can also be printed separately.
Python3
from datetime import time
Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)
Output:
hour = 11
minute = 34
second = 56
microsecond = 0
Example 3: Convert Time object to String
We can convert time object to string using the isoformat() method.
Python3
from datetime import time
# Creating Time object
Time = time(12,24,36,1212)
# Converting Time object to string
Str = Time.isoformat()
print("String Representation:", Str)
print(type(Str))
Output
String Representation: 12:24:36.001212
<class 'str'>
List of Time class Methods
Function Name Description
Returns tzinfo.dst() is tzinfo is not
dst()
None
Returns a time object from the string
fromisoformat()
representation of the time
Returns the string representation of
isoformat()
time from the time object
Changes the value of the time object
replace()
with the given parameter
Returns a string representation of the
strftime()
time with the given format
Returns tzinfo.tzname() is tzinfo is
tzname()
not None
Returns tzinfo.utcffsets() is tzinfo is
utcoffset()
not None
Python Datetime class
The DateTime class contains information on both date and time. Like a date
object, datetime assumes the current Gregorian calendar extended in both
directions; like a time object, datetime assumes there are exactly 3600*24
seconds in every day.
Constructor Syntax:
class datetime.datetime(year, month, day, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None, *, fold=0)
The year, month, and day arguments are mandatory. tzinfo can be None, rest all
the attributes must be an integer in the following range –
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
fold in [0, 1]
Note – Passing an argument other than integer will raise a TypeError and
passing arguments outside the range will raise ValueError.
DateTime object representing DateTime in Python
Python3
# Python program to
# demonstrate datetime object
from datetime import datetime
# Initializing constructor
a = datetime(1999, 12, 12)
print(a)
# Initializing constructor
# with time parameters as well
a = datetime(1999, 12, 12, 12, 12, 12, 342380)
print(a)
Output:
1999-12-12 00:00:00
1999-12-12 12:12:12.342380
Get year, month, hour, minute, and timestamp
After creating a DateTime object, its attributes can also be printed separately.
Python3
from datetime import datetime
a = datetime(1999, 12, 12, 12, 12, 12)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())
Output:
year = 1999
month = 12
hour = 12
minute = 12
timestamp = 945000732.0
Current date and time
You can print the current date and time using the Datetime.now() function.
now() function returns the current local date and time.
Python3
from datetime import datetime
# Calling now() function
today = datetime.now()
print("Current date and time is", today)
Output:
Current date and time is 2019-10-25 11:12:11.289834
Convert Python Datetime to String
We can convert Datetime to string in Python using the datetime.strftime and
datetime.isoformat methods.
Python3
from datetime import datetime as dt
# Getting current date and time
now = dt.now()
string = dt.isoformat(now)
print(string)
print(type(string))
Output
2021-08-19T18:13:25.346259
<class 'str'>
List of Datetime Class Methods
Function Name Description
Returns the DateTime object
astimezone()
containing timezone information.
Combines the date and time objects
combine()
and return a DateTime object
Returns a string representation of
ctime()
date and time
date() Return the Date class object
Returns a datetime object from the
fromisoformat() string representation of the date and
time
Returns a date object from the
proleptic Gregorian ordinal, where
fromordinal() January 1 of year 1 has ordinal 1.
The hour, minute, second, and
microsecond are 0
Return date and time from POSIX
fromtimestamp()
timestamp
Returns a tuple year, week, and
isocalendar()
weekday
Return the string representation of
isoformat()
date and time
Function Name Description
Returns the day of the week as
isoweekday() integer where Monday is 1 and
Sunday is 7
Returns current local date and time
now()
with tz parameter
Changes the specific attributes of the
replace()
DateTime object
Returns a string representation of the
strftime() DateTime object with the given
format
Returns a DateTime object
strptime()
corresponding to the date string
time() Return the Time class object
Returns an object of type
timetuple()
time.struct_time
timetz() Return the Time class object
Return local DateTime with tzinfo as
today()
None
Function Name Description
Return the proleptic Gregorian
toordinal() ordinal of the date, where January 1
of year 1 has ordinal 1
tzname() Returns the name of the timezone
utcfromtimestamp() Return UTC from POSIX timestamp
utcoffset() Returns the UTC offset
utcnow() Return current UTC date and time
Returns the day of the week as
weekday() integer where Monday is 0 and
Sunday is 6
Python Timedelta Class
Python timedelta class is used for calculating differences in dates and also can
be used for date manipulations in Python. It is one of the easiest ways to
perform date manipulations.
Constructor syntax:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0)
Returns : Date
Add days to DateTime object
The timedelta function demonstration
Python3
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print("initial_date", str(ini_time_for_now))
# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now +
timedelta(days=730)
future_date_after_2days = ini_time_for_now +
timedelta(days=2)
# printing calculated future_dates
print('future_date_after_2yrs:',
str(future_date_after_2yrs))
print('future_date_after_2days:',
str(future_date_after_2days))
Output:
initial_date 2019-10-25 12:01:01.227848
future_date_after_2yrs: 2021-10-24 12:01:01.227848
future_date_after_2days: 2019-10-27 12:01:01.227848
Difference between two date and times
Date and Time differences can also be found using this class.
Python3
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
ini_time_for_now = datetime.now()
# printing initial_date
print("initial_date", str(ini_time_for_now))
# Some another datetime
new_final_time = ini_time_for_now + \
timedelta(days=2)
# printing new final_date
print("new_final_time", str(new_final_time))
# printing calculated past_dates
print('Time difference:', str(new_final_time -
ini_time_for_now))
Output:
initial_date 2019-10-25 12:02:32.799814
new_final_time 2019-10-27 12:02:32.799814
Time difference: 2 days, 0:00:00
Operations supported by Timedelta Class
Operator Description
Addition (+) Adds and returns two timedelta objects
Subtracts and returns two timedelta
Subtraction (-)
objects
Multiplies timedelta object with float or
Multiplication (*)
int
Divides the timedelta object with float
Division (/)
or int
Divides the timedelta object with float
Floor division (//) or int and return the int of floor value of
the output
Divides two timedelta object and
Modulo (%)
returns the remainder
+(timedelta) Returns the same timedelta object
-(timedelta) Returns the resultant of -1*timedelta
Returns the +(timedelta) if
abs(timedelta) timedelta.days > 1=0 else returns -
(timedelta)
Returns a string in the form (+/-)
str(timedelta)
day[s], HH:MM:SS.UUUUUU
Operator Description
Returns the string representation in the
repr(timedelta)
form of the constructor call
Format DateTime in Python
Formatting DateTime can be very necessary as the date representation may
differ from place to place. In some countries, it can be yyyy-mm-dd and in other
countries, it can be dd-mm-yyyy. To format Python Datetime strptime and
strftime functions can be used.
Python Datetime strftime
A strftime() method converts the given date, time, or DateTime object to the
string representation of the given format.
Python Datetime format
Python program to demonstrate strftime() function
Python3
from datetime import datetime as dt
# Getting current date and time
now = dt.now()
print("Without formatting", now)
# Example 1
s = now.strftime("%A %m %-Y")
print('\nExample 1:', s)
# Example 2
s = now.strftime("%a %-m %y")
print('\nExample 2:', s)
# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)
# Example 4
s = now.strftime("%H:%M:%S")
print('\nExample 4:', s)
Output
Without formatting 2021-08-19 18:16:25.881661
Example 1: Thursday 08 2021
Example 2: Thu 8 21
Example 3: 6 PM 25
Example 4: 18:16:25
Note: For more information, refer to strftime() method.
Python DateTime strptime
The strptime() creates a DateTime object from the given string.
Example: DateTime strptime
Python3
# import datetime module from datetime
from datetime import datetime
# consider the time stamps from a list in string
# format DD/MM/YY H:M:S.micros
time_data = ["25/05/99 02:35:8.023",
"26/05/99 12:45:0.003",
"27/05/99 07:35:5.523", "28/05/99
05:15:55.523"]
# format the string in the given format :
day/month/year
# hours/minutes/seconds-micro seconds
format_data = "%d/%m/%y %H:%M:%S.%f"
# Using strptime with datetime we will format
string
# into datetime
for i in time_data:
print(datetime.strptime(i, format_data))
Output
1999-05-25 02:35:08.023000
1999-05-26 12:45:00.003000
1999-05-27 07:35:05.523000
1999-05-28 05:15:55.523000
Python DateTime.tzinfo()
The datetime.now() function contains no information regarding time zones. It
only makes use of the current system time. Tzinfo is an abstract base class in
Python. It cannot be directly instantiated. A concrete subclass must derive from
this abstract class and implement the methods offered by it.
List of Python DateTime.tzinfo() Objects
Function Name Description
Returns tzinfo.dst() is tzinfo is not
dst()
None
The purpose of this function is to
adjust the date time data,
fromutc()
returning an equivalent DateTime in
self’s local time.
Returns tzinfo.tzname() is tzinfo is
tzname()
not None
Returns tzinfo.utcffsets() is tzinfo is
utcoffset()
not None
Example
The tzinfo class instance can be provided to the DateTime and time object
constructors. It is used in scenarios such as converting local time to UTC or
accounting for daylight savings time.
Python3
import datetime as dt
from dateutil import tz
tz_string =
dt.datetime.now(dt.timezone.utc).astimezone().tzname()
print("datetime.now() :", tz_string)
NYC = tz.gettz('Europe / Berlin')
dt1 = dt.datetime(2022, 5, 21, 12, 0)
dt2 = dt.datetime(2022, 12, 21, 12, 0, tzinfo=NYC)
print("Naive Object :", dt1.tzname())
print("Aware Object :", dt2.tzname())
Output:
datetime.now() : IST
Naive Object : None
Aware Object : None
Python DateTime timezone
Timezones in DateTime can be used in the case where one might want to
display time according to the timezone of a specific region. This can be done
using the pytz module of Python. This module serves the date-time conversion
functionalities and helps users serving international client bases.
Python3
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
timezones = ['Asia/Kolkata', 'Europe/Kiev',
'America/New_York']
for tzone in timezones:
# Convert to Asia/Kolkata time zone
now_asia =
now_utc.astimezone(timezone(tzone))
print(now_asia.strftime(format))
Output
2021-08-19 18:27:28 UTC+0000
2021-08-19 23:57:28 IST+0530
2021-08-19 21:27:28 EEST+0300
2021-08-19 14:27:28 EDT-0400