0% found this document useful (0 votes)
21 views36 pages

Python (Unit Ii)

This document covers Python string handling, including creation, operations, and slicing, as well as object-oriented programming concepts such as classes, objects, and encapsulation. It explains how to manipulate strings, the immutability of strings, and the use of escape sequences. Additionally, it introduces the basics of classes and objects in Python, including attributes, methods, and the significance of the __init__ method.

Uploaded by

gouravkangle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views36 pages

Python (Unit Ii)

This document covers Python string handling, including creation, operations, and slicing, as well as object-oriented programming concepts such as classes, objects, and encapsulation. It explains how to manipulate strings, the immutability of strings, and the use of escape sequences. Additionally, it introduces the basics of classes and objects in Python, including attributes, methods, and the significance of the __init__ method.

Uploaded by

gouravkangle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Python Programming | 2024

UNIT 2
String Handling, Classes, Modules and Package
2.1 Strings, String operations and String Slicing

2.1.1. Python Strings

Python string is the collection of the characters surrounded by single quotes,


double quotes, or triple quotes. The computer does not understand the
characters; internally, it stores manipulated character as the combination of the
0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say


that Python strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes. Python allows us to use single quotes, double quotes,
or triple quotes to create the string.

Here, if we check the type of the variable str using a Python script.

Creating a String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
CODE;-
# Python Program for
# Creation of String
#
# Creating a String
# with single Quotes
String1 = 'Welcome to the Latur'
print("String with the use of Single Quotes: ")
print(String1)

OUTPUT:-
String with the use of Single Quotes:
Welcome to the Latur

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
2.1.2. String operations
Accessing characters in Python

 In Python, individual characters of a String can be accessed by using the


method of Indexing.
 Indexing allows negative address references to access characters from
the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.

CODE:-
# Python Program to Access
# characters of String

String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

OUTPUT:-
Initial String:
HELLOCOCSITLATUR

First character of String is:


H
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

Last character of String is:


R

Deleting/Updating from a String

 In Python, Updation or deletion of characters from a String is not


allowed. This will cause an error because item assignment or item
deletion from a String is not supported.
 Although deletion of the entire String is possible with the use of a built-
in del keyword.
 This is because Strings are immutable, hence elements of a String cannot
be changed once it has been assigned.
 Only new strings can be reassigned to the same name.
CODE:-
# Python Program to Update
# character of a String

String1 = "Hello, I'm a AB"


print("Initial String: ")
print(String1)

# Updating a character
# of the String
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)

OUTPUT:-
Initial String:
Hello, I'm a AB
Traceback (most recent call last):
File "f:\COCSIT\B.Sc(CS)- TY(Python)\File_Handling\main.py", line 10, in
<module>
String1[2] = 'p'
TypeError: 'str' object does not support item assignment

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
CODE:-
# Python Program to Delete
# characters from a String

String1 = "Hello, I'm a AB"


print("Initial String: ")
print(String1)

# Deleting a character
# of the String
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)

OUTPUT:-
Initial String:
Hello, I'm a AB
Traceback (most recent call last):
File "f:\COCSIT\B.Sc(CS)-
TY(Python)\File_Handling\main.py", line 10, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion

Deleting Entire String:


 Deletion of the entire string is possible with the use of del keyword. Further, if we
try to print the string, this will produce an error because String is deleted and is
unavailable to be printed.
CODE:-
# Python Program to Delete
# entire String

String1 = "Hello, I'm a AB"


print("Initial String: ")
print(String1)

# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
OUTPUT:-
Initial String:
Hello, I'm a Geek

Deleting entire String:


Traceback (most recent call last):
File "f:\COCSIT\B.Sc(CS)-
TY(Python)\File_Handling\main.py", line 12, in <module>
print(String1)
NameError: name 'String1' is not defined

Escape Sequencing in Python

 While printing Strings with single and double quotes in it


causes SyntaxError because String already contains Single and Double
Quotes and hence cannot be printed with the use of either of these.
 Hence, to print such a String either Triple Quotes are used or Escape
sequences are used to print such Strings.
 Escape sequences start with a backslash and can be interpreted
differently. If single quotes are used to represent a string, then all the
single quotes present in the string must be escaped and same is done for
Double Quotes.
CODE:-
# Python Program for
# Escape Sequencing
# of String

# Initial String
String1 = '''I'm a "AB"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote


String1 = 'I\'m a "AB"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes


String1 = "I'm a \"AB\""
print("\nEscaping Double Quotes: ")

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print(String1)

# Printing Paths with the


# use of Escape Sequences
String1 = "C:\\Python\\AB\\"
print("\nEscaping Backslashes: ")
print(String1)

OUTPUT:-
Initial String with use of Triple Quotes:
I'm a "AB"

Escaping Single Quote:


I'm a "AB"

Escaping Double Quotes:


I'm a "AB"

Escaping Backslashes:
C:\Python\AB\

2.1.3. String Slicing


Python slicing is about obtaining a sub-string from the given string by slicing
it respectively from start to end.
Python slicing can be done in two ways.
 slice() Constructor
 Extending Indexing

slice() Constructor
The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Syntax:
 slice(stop)
 slice(start, stop, step)
Parameters:
start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each
index for slicing.
Return Type: Returns a sliced object containing elements in the given range
only.
Index tracker for positive and negative index:
Negative comes into considers when tracking the string in reverse.

CODE:-
# Python program to demonstrate
# string slicing
# String slicing
String ='ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing")

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print(String[s1])
print(String[s2])
print(String[s3])

Output:
String slicing
AST
SR
GITA

Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This
is an easy and convenient way to slice a string both syntax wise and execution
wise.
Syntax
string[start:end:step]
start, end and step have the same mechanism as slice() constructor.

CODE:-
# Python program to demonstrate
# string slicing

# String slicing
String ='ASTRING'

# Using indexing sequence


print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# Prints string in reverse


print("\nReverse String")
print(String[::-1])

OUTPUT:-
AST
SR
GITA

Reverse String
GNIRTSA
 Python OOPs Concepts

In Python, object-oriented Programming (OOPs) is a programming paradigm


that
uses objects and classes in programming.
It aims to implement real-world entities like inheritance, polymorphisms,
encapsulation, etc. in the programming.
The main concept of OOPs is to bind the data and the functions that work on
that
together as a single unit so that no other part of the code can access this data.
Main Concepts of Object-Oriented Programming (OOPs)
 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

Python Classes and Objects

A class is a user-defined blueprint or prototype from which objects are created.


Classes provide a means of bundling data and functionality together. Creating
a new class creates a new type of object, allowing new instances of that type to
be made.
Each class instance can have attributes attached to it for maintaining its state.
Class instances can also have methods (defined by their class) for modifying
their state.
To understand the need for creating a class let’s consider an example, let’s say
you wanted to track the number of dogs that may have different attributes like
breed, age. If a list is used, the first element could be the dog’s breed while the
second element could represent its age.
Let’s suppose there are 100 different dogs, then how would you know which
element is supposed to be which? What if you wanted to add other properties
to these dogs? This lacks organization and it’s the exact need for classes.
Class creates a user-defined data structure, which holds its own data members
and member functions, which can be accessed and used by creating an instance
of that class. A class is like a blueprint for an object.

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator.
Eg.: Myclass.Myattribute
Class Definition Syntax:

class ClassName:
# Statement-1
.
.
.
# Statement-N

CODE:-
class Student:
pass

In the above example, the class keyword indicates that you are creating a class
followed by the name of the class.

Class Objects
An Object is an instance of a Class. A class is like a blueprint while an instance
is a copy of the class with actual values. It’s not an idea anymore, it’s an actual
dog, like a dog of breed pug who’s seven years old. You can have many dogs
to create many different instances, but without the class as a guide, you would
be lost, not knowing what information is required.
An object consists of :
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.

CODE:-
class Student:
name = "abc" #attribute1
age = 21 #attribute2

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
def myfun(self):
print(self.name)
print(self.age)
object = Student()
object.myfun()

OUTPUT:-
abc
21

In the above example, an object is created which is basically a object named.


This class only has two class attributes that tell us that abc is a Student and a
having age 21.
The self
 Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python
provides it.
 If we have a method that takes no arguments, then we still have to have one
argument.
 This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is
automatically converted by Python into MyClass.method(myobject, arg1, arg2)
– this is all the special self is about.

__init__ method
The __init__ method is similar to constructors in C++ and Java. Constructors
are used to initializing the object’s state. Like methods, a constructor also
contains a collection of statements(i.e. instructions) that are executed at the
time of Object creation. It runs as soon as an object of a class is instantiated.
The method is useful to do any initialization you want to do with your object.
CODE:-
# A Sample class with init method
class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('ABC')
p.say_hi()

Output:
Hello, my name is ABC

Class and Instance Variables


Instance variables are for data, unique to each instance and class variables are
for attributes and methods shared by all instances of the class. Instance
variables are variables whose value is assigned inside a constructor or method
with self whereas class variables are variables whose value is assigned in the
class.
Defining instance variable using a constructor.

CODE:-
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for STUDENT


class Student:

# Class Variable
person = 'student'

# The init method or constructor


def __init__(self, value1, value2):

# Instance Variable
self.name = value1
self.age = value2

# Objects of Student class


obj1 = Student("abc", 22)
obj2 = Student("xyz",23)
print(obj1.name)
print(obj2.name)
print(obj1.age)
print(obj2.age)

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
OUTPUT:-
abc
xyz
22
23

Encapsulation

Encapsulation is one of the fundamental concepts in object-oriented


programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit. This puts restrictions on accessing variables
and methods directly and can prevent the accidental modification of data. To
prevent accidental change, an object’s variable can only be changed by an
object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is
member functions, variables, etc.

CODE:-
# Python program to
# demonstrate private members

# Creating a Base class


class Base:
def __init__(self):
self.a = "HelloCocsitHello"
self.__c = "HelloCocsitHello"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
print("Calling private member of base class: ")
print(self.__c)

# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class

OUTPUT:-
HelloCocsitHello

Types of inheritance:-

Inheritance is defined as the capability of one class to derive or inherit the


properties from some other class and use it whenever needed. Inheritance
provides the following properties:

 It represents real-world relationships well.


 It provides reusability of code. We don’t have to write the same code again
and again. Also, it allows us to add more features to a class without
modifying it.
 It is transitive in nature, which means that if class B inherits from another
class A, then all the subclasses of B would automatically inherit from class
A.

Example:

# A Python program to demonstrate

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# inheritance

# Base class or Parent class

class Child:

# Constructor

def __init__(self, name):

self.name = name

# To get name

def getName(self):

return self.name

# To check if this person is student

def isStudent(self):

return False

# Derived class or Child class

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

class Student(Child):

# True is returned

def isStudent(self):

return True

# Driver code

# An Object of Child

std = Child("Ram")

print(std.getName(), std.isStudent())

# An Object of Student

std = Student("Shivam")

print(std.getName(), std.isStudent())

Output:

Ram False
Shivam True

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Types of Inheritance in Python
Types of Inheritance depends upon the number of child and parent classes
involved. There are four types of inheritance in Python:

Single Inheritance: Single inheritance enables a derived class to inherit


properties from a single parent class, thus enabling code reusability and the
addition of new features to existing code.

Example:

# Python program to demonstrate

# single inheritance

# Base class

class Parent:

def func1(self):

print("This function is in parent class.")

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# Derived class

class Child(Parent):

def func2(self):

print("This function is in child class.")

# Driver's code

object = Child()

object.func1()

object.func2()

Output:

This function is in parent class.


This function is in child class.

Multiple Inheritance: When a class can be derived from more than one base
class this type of inheritance is called multiple inheritance. In multiple
inheritance, all the features of the base classes are inherited into the derived
class.

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

Example:

# Python program to demonstrate

# multiple inheritance

# Base class1

class Mother:

mothername = ""

def mother(self):

print(self.mothername)

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# Base class2

class Father:

fathername = ""

def father(self):

print(self.fathername)

# Derived class

class Son(Mother, Father):

def parents(self):

print("Father :", self.fathername)

print("Mother :", self.mothername)

# Driver's code

s1 = Son()

s1.fathername = "RAM"

s1.mothername = "SITA"

s1.parents()

Output:
Father : RAM
Mother : SITA
Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
further inherited into the new derived class. This is similar to a relationship
representing a child and grandfather.

Example:

# Python program to demonstrate

# multilevel inheritance

# Base class

class Grandfather:

def __init__(self, grandfathername):

self.grandfathername = grandfathername

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# Intermediate class

class Father(Grandfather):

def __init__(self, fathername, grandfathername):

self.fathername = fathername

# invoking constructor of Grandfather class

Grandfather.__init__(self, grandfathername)

# Derived class

class Son(Father):

def __init__(self,sonname, fathername, grandfathername):

self.sonname = sonname

# invoking constructor of Father class

Father.__init__(self, fathername, grandfathername)

def print_name(self):

print('Grandfather name :', self.grandfathername)

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

print("Father name :", self.fathername)

print("Son name :", self.sonname)

# Driver code

s1 = Son('Prince', 'Rampal', 'Lal mani')

print(s1.grandfathername)

s1.print_name()

Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance: When more than one derived classes are created
from a single base this type of inheritance is called hierarchical inheritance. In
this program, we have a parent (base) class and two child (derived) classes.

Example:

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# Python program to demonstrate

# Hierarchical inheritance

# Base class

class Parent:

def func1(self):

print("This function is in parent class.")

# Derived class1

class Child1(Parent):

def func2(self):

print("This function is in child 1.")

# Derivied class2

class Child2(Parent):

def func3(self):

print("This function is in child 2.")

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# Driver's code

object1 = Child1()

object2 = Child2()

object1.func1()

object1.func2()

object2.func1()

object2.func3()

Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.

Hybrid Inheritance: Inheritance consisting of multiple types of inheritance is


called hybrid inheritance.

Example:

# Python program to demonstrate

# hybrid inheritance

class School:

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

def func1(self):

print("This function is in school.")

class Student1(School):

def func2(self):

print("This function is in student 1. ")

class Student2(School):

def func3(self):

print("This function is in student 2.")

class Student3(Student1, School):

def func4(self):

print("This function is in student 3.")

# Driver's code

object = Student3()

object.func1()

object.func2()

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Output:
This function is in school.
This function is in student 1.

Python Modules
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
runnable code. Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
Example: create a simple module

# A simple module, calc.py

def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)

Import Module in Python – Import statement


We can import the functions, classes defined in a module to another module
using the import statement in some other Python source file.

Syntax:
import module

When the interpreter encounters an import statement, it imports the module if


the module is present in the search path. A search path is a list of directories that
the interpreter searches for importing a module. For example, to import the
module calc.py, we need to put the following command at the top of the script.

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.

Example: Importing modules in Python

# importing module calc.py

import calc

print(calc.add(10, 2))

Output:
12

The from import Statement


Python’s from statement lets you import specific attributes from a module
without importing the module as a whole.

Example: Importing specific attributes from the module

# importing sqrt() and factorial from the

# module math

from math import sqrt, factorial

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

# are required.

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

print(sqrt(16))

print(factorial(6))

Output:
4.0
720

Import all Names – From import * Statement


The * symbol used with the from import statement is used to import all the
names from a module to a current namespace.

Syntax:
from module_name import *

The use of * has its advantages and disadvantages. If you know exactly what
you will be needing from the module, it is not recommended to use *, else do
so.

Example: Importing all names

# importing sqrt() and factorial from the

# module math

from math import *

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# are required.

print(sqrt(16))

print(factorial(6))

Output
4.0
720

Python datetime module

In Python, date and time are not a data type of their own, but a module
named datetime 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.
Python Datetime module supplies classes to work with date and time. These
classes provide a number of functions to deal with dates, times and time
intervals. Date and datetime are an object in Python, so when you manipulate
them, you are actually manipulating objects and not string 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.
 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.
 datetime – Its a combination of date and time along with the attributes year,
month, day, hour, minute, second, microsecond, and tzinfo.
 timedelta – A duration expressing the difference between two date, time, or
datetime instances to microsecond resolution.
 tzinfo – It provides time zone information objects.
 timezone – A class that implements the tzinfo abstract base class as a fixed
offset from the UTC (New in version 3.2).

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024
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.
Constructor of this class needs three mandatory arguments year, month and
date.
Constructor 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.

Example 1: Date object representing date in Python

# Python program to

# demonstrate date class

# import the date class

from datetime import date

# initializing constructor

# and passing arguments in the

# format year, month, date

my_date = date(1996, 12, 11)

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

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)

Example 2: Get Current Date

To return the current local date today() function of date class is used. today()
function comes with several attributes (year, month and day). These can be
printed individually.

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

# 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

Example 3: 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.

from datetime import date

# date object of today's date

today = date.today()

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

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

Example 4: 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.

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

Example 5: Convert Date to String

We can convert date object to a string representation using two functions


isoformat() and strftime().

 Python3

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur
Python Programming | 2024

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'>

Prepared by :
Dr. V. V Bhosle ,COCSIT , Latur

You might also like