0% found this document useful (0 votes)
6 views16 pages

Python Modules and Packages Explained

The document provides an overview of Python modules and packages, explaining how to create and import them, as well as the differences between built-in, user-defined, and third-party modules. It also covers the datetime and time modules, detailing their functionalities and methods for handling dates and times. Additionally, it discusses the calendar module and provides examples of using various date and time functions.
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)
6 views16 pages

Python Modules and Packages Explained

The document provides an overview of Python modules and packages, explaining how to create and import them, as well as the differences between built-in, user-defined, and third-party modules. It also covers the datetime and time modules, detailing their functionalities and methods for handling dates and times. Additionally, it discusses the calendar module and provides examples of using various date and time functions.
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

UNIT-IV

Python Module
A module in Python is simply a file that contains Python code — functions, variables, or classes,
which you can reuse in other programs.
It helps in organizing code logically and avoiding repetition.
The file name (without .py) becomes the module name.

For example, if you create a file named [Link]:

# [Link]
def greet(name):
return (f"Hello, {name}!")

Then mymodule is a module that can be imported and used in another Python file.

Importing Modules in Python


Python provides multiple ways to import modules:

a) Import the whole module


import math
print([Link](16)) # Using sqrt function from math module → Output: 4.0

We use the module name (math) followed by a dot (.) to access its functions.

b) Import with an alias


You can give a shorter name using as:

import math as m

print([Link]) # Output: 3.141592653589793

c) Import specific functions or variables


You can import only what you need:
from math import sqrt, pi

print(sqrt(25)) # Output: 5.0


print(pi) # Output: 3.141592653589793

Here, you can use sqrt() directly without prefixing math.

d) Import all names (not recommended)


from math import *
print(sin(0)) # Output: 0.0

This imports everything from the module into the current namespace.
Not recommended because it can lead to naming conflicts and make code unclear.
Types of Modules

Built-in Modules → Already included with Python


Examples: math, random, datetime, os, sys, json
User-defined Modules → Created by you (e.g., [Link])
Third-party Modules → Installed using pip
Examples: numpy, pandas, requests

pip install requests

import requests
response = [Link]("[Link]

Example:
Suppose we have a module [Link]:
# [Link]
def add(a, b):
return a + b

def multiply(a, b):


return a * b

In another file:

import calculator
print([Link](2, 3)) # Output: 5
print([Link](4, 5)) # Output: 20

Python Package
A Python module may contain several classes, functions, variables, etc. whereas a Python
package can contain several modules. In simpler terms a package is folder that contains various
modules as files.

Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and [Link]
create this module follow the below steps –
 Create a folder named mypckg.
 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.

[Link]
def greet():
print("Welcome to python")
[Link]
def sum(a, b):
return a+b

The hierarchy of our package looks like this –


mypckg
|
|
--- init .py
|
|
---[Link]
|
|
---[Link]

[Link] helps the Python interpreter to recognize the folder as package. It also specifies
the resources to be imported from the modules. If the __init__.py is empty this means that all
the functions of the modules will be imported. We can also specify the functions from each
module to be made available.

Importing module when __init__.py is empty


Example 1
from mypckg import mod1
from mypckg import mod2

[Link]()
[Link](3,4)

Output:
Welcome to Python
7

Example 2
import mypckg.mod1
import mypckg.mod2

[Link]()
[Link](3,4)
Output:
Welcome to Python
7

Example 3
from mypckg.mod1 import greet
from mypckg.mod2 import sum

greet()
sum(3,4)
Output:
Welcome to Python
7

Importing module when __init__.py is not empty


we can also create the __init__.py file for the above module as –
__init__.py
from .mod1 import greet
from .mod2 import sum

This [Link] will only allow the greet and sum functions from the mod1 and mod2 modules
to be imported.

Example 1:
import mypckg
[Link]()
[Link](3,4)

Output:
Welcome to Python
7

Example 2
from mypckg import greet,sum
greet()
sum(3,4)

Output:
Welcome to Python
7

How to Reload a Module


When you import a module in Python, it is loaded only once into memory.
If you change the module’s code (for example, edit the .py file) after importing, those changes
won’t automatically reflect unless you reload the module.

Reloading a module means forcing Python to re-import it and update its definitions without
restarting the interpreter.

Python provides the function [Link]() to reload a module.


Step 1: Import the module
import mod1
Step 2: Import the reload function
import importlib

Step 3: Reload the module


[Link](mypckg.mod1)

Example
Suppose you have a file named [Link]:
def greet():
print("Welcome to Python")

In your Python shell:


import mod1
[Link]()
Output:
Welcome to Python

Now, edit [Link] to:


def greet():
print("Hello, World! Updated code.")

If you run [Link]() again, it still prints the old message because the module is already
loaded.

Reload it:
import importlib
[Link](mypckg.mod1)
[Link]()
Output:
Hello, World! Updated code.
The module is now reloaded and reflects the latest changes.

Python Date, and Time module


Python provides the datetime module to work with real dates and times. In real-world
applications, we need to work with the date and time. Python enables us to schedule our Python
script to run at a particular time.
In Python, the date is not a data type, but we can work with the date objects by importing the
module named with datetime, time, and calendar.

o date - It is a naive ideal date. It consists of the year, month, and day as attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour,
minute, second, microsecond, and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
o timedelta - It represents the difference between two dates, time or datetime instances to
microsecond resolution.
o tzinfo - It provides time zone information objects.
o timezone - It is included in the new version of Python. It is the class that implements the tzinfo
abstract base class.

Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of
the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick
can be seen as the smallest unit to measure the time.

Time Module
The time module in Python provides various functions to work with time and dates, including:
• Accessing the current time
• Pausing the program for a specific duration
• Measuring execution time
• Formatting and converting time values
• Before using, you must import it as: import time

Commonly Used Methods in time Module


a) [Link]()
Returns the current time in seconds since the Unix epoch (January 1, 1970).
Return type: float.
print([Link]())
Output: 1728204844.478022 # This means 1,728,204,844 seconds have passed since Jan 1, 1970
(UTC)
Use: Measuring execution time, logging, timestamps.

b) [Link](seconds)
[Link](3) # pauses for 3 seconds
Pauses the execution of the program for the specified number of seconds.
Useful for delays, waiting, or simulating long-running tasks.

c) [Link]([secs])
Converts a time in seconds since the epoch to a readable string.
If no argument is given, it uses the current time.

print([Link]()) #Output: Thu Oct 30 [Link] 2025


print([Link](0)) # Output: Thu Jan 1 [Link] 1970 #Epoch time
print([Link](1761790009.556)) #Output: Thu Oct 30 [Link] 2025

d) [Link]([secs])
Converts a time in seconds (or current time if not given) into a time.struct_time object in local
time. Useful for extracting specific time parts like year, month, etc.
print([Link]())
t = [Link]()
print(t.tm_year)
print(t.tm_hour)
[Link](1760414228.1569998)
Output:
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=30, tm_hour=8, tm_min=52, tm_sec=53, tm_wday=3,
tm_yday=303, tm_isdst=0)
2025
8
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=14, tm_hour=9, tm_min=27, tm_sec=8, tm_wday=1,
tm_yday=287, tm_isdst=0)

e) [Link]([secs]): Same as localtime(), but returns UTC (Coordinated Universal Time)


time instead of local time.

print([Link]())
Output:
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=30, tm_hour=3, tm_min=28, tm_sec=54, tm_wday=3,
tm_yday=303, tm_isdst=0)

f) [Link](t): Converts a struct_time object (like from localtime) back into seconds since
the epoch. It’s the inverse of localtime()

import time

t = [Link]() # get current local time as struct_time


print("Struct time:", t)

seconds = [Link](t)
print("Seconds since epoch:", seconds)
Output (example):

output:
Struct time: time.struct_time(tm_year=2025, tm_mon=10, tm_mday=26, tm_hour=10,
tm_min=30, tm_sec=0, tm_wday=6, tm_yday=299, tm_isdst=0)

Seconds since epoch: 1761468000.0

g) [Link]([t]): Converts a struct_time object into a string.

print([Link]())
Output:

Thu Oct 30 [Link] 2025

Date module:
[Link] − The earliest representable date, date(MINYEAR, 1, 1).
[Link] − The latest representable date, date(MAXYEAR, 12, 31).
[Link] − The smallest possible difference between non-equal date objects.
[Link] − Between MINYEAR and MAXYEAR inclusive.
[Link] − Between 1 and 12 inclusive.
[Link] − Between 1 and the number of days in the given month of the given year.

Example:
from datetime import date
# Getting min date
mindate = [Link]
print("Minimum Date:", mindate)
# Getting max date
maxdate = [Link]
print("Maximum Date:", maxdate)
Date1 = date(2023, 4, 20)
print("Year:", [Link])
print("Month:", [Link])
print("Day:", [Link])

Output −
Minimum Date: 0001-01-01
Maximum Date: 9999-12-31
Year: 2023
Month: 4
Day: 20

Methods in Date Module:


 today() − Return the current local date.
 fromtimestamp(timestamp) − Return the local date corresponding to the POSIX timestamp,
such as is returned by [Link](). A POSIX timestamp (also known as Unix timestamp or epoch
time) is a number that represents the number of seconds elapsed since January 1, 1970, [Link]
UTC (It is the primary time reference that all time zones are based on).
For example:
ts = 1735233600
# Convert timestamp to local date and time
local_dt = [Link](ts)
print("Local Date and Time:", local_dt)

Local Date and Time: 2024-12-26


 fromordinal(ordinal) − Return the date corresponding to the proleptic Gregorian
ordinal, where January 1 of year 1 has ordinal 1. An ordinal date is simply the number of days
that have passed since January 1 of year 1 (1-1-1) in the proleptic Gregorian calendar.
Example:
ordinal_value = 738885 #days
# Convert ordinal to date
dt = [Link](ordinal_value)
print("Converted Date:", dt)

Converted Date: 2023-12-31

 fromisoformat(date_string) − Return a date corresponding to a date_string given in any


valid ISO 8601 format, except ordinal dates. ISO 8601 is an international standard for
representing dates and times.
Examples:
"2024-12-27" → date only
"2024-12-27T[Link]" → date + time
"2024-12-27T[Link]+05:30" → date + time + timezone

dt = [Link]('2024-12-25')
print(dt)

2024-12-25

Difference between two timedelta objects


Example1.
import datetime as dt
t1 = [Link](12,15)
t2 = [Link](4,11)
t3 = t1 - t2
print("t3 =", t3)
Output:
t3 = 8 days, [Link]

Example 2.
from datetime import timedelta
t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)
t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
Output: t3 = 14 days, [Link]

Python datetime Module


The datetime module in Python provides classes for manipulating dates and times.
It helps you create, format, compare, and calculate with dates and times easily.

1. [Link](): Returns the current local date and time.

from datetime import datetime


print([Link]())
# Output: 2025-10-26 [Link].12345
2. [Link](): Returns the current local date and time (similar to now(), but without
timezone support).

from datetime import datetime


print([Link]())
# Output: 2025-10-31 [Link].695000

3. [Link](): Extracts only the date part from a datetime object.

from datetime import datetime


print([Link]().date())
# Output: 2025-10-26

4. [Link](): Extracts only the time part from a datetime object.

from datetime import datetime


print([Link]().time())
# Output: [Link].543210

5. [Link](format): Converts a datetime object to a string using a format.

from datetime import datetime


print([Link]().strftime("%Y-%m-%d %H:%M:%S"))
# Output: 2025-10-26 [Link]

6. [Link](): Returns the day of the week (0 = Monday, 6 = Sunday).

from datetime import datetime


print(datetime(2025, 10, 26).weekday())
# Output: 6

7. [Link](): Returns a string representation of datetime in ISO 8601 format.

from datetime import datetime


print([Link]().isoformat())
# Output: 2025-10-26T[Link].123456

Comparison of two dates


We can compare two dates by using the comparison operators like >, >=, <, and <=.

from datetime import datetime


dt1 = datetime(2025, 10, 26, 8, 30)
dt2 = datetime(2025, 10, 26, 12, 45)
print("dt1:", dt1)
print("dt2:", dt2)
if dt1 < dt2:
print("dt1 is earlier than dt2")
else:
print("dt1 is later than or equal to dt2")
Output:
dt1 is earlier than dt2

You can also find out the difference between two dates.

from datetime import date


d1 = date(2025, 10, 25)
d2 = date(2025, 11, 2)
diff = d2 - d1
print("Difference:", [Link], "days")
Output:
Difference: 8 days

Python calendar Module

The calendar module in Python provides functions to work with calendars, dates, months, and
leap years.
It is mainly used for displaying and analyzing calendar data, not for date/time arithmetic

Commonly Used Functions in calendar Module

[Link](year, w=2, l=1, c=6, m=3)

Parameter Meaning

year Year to generate calendar for

w Width between day columns

l Lines per week

c Space between month columns

m Number of months per row

[Link](year, w=2, l=1, c=6, m=3)


Prints the full-year calendar (similar to [Link]() but directly outputs instead of
returning a string).

[Link](year,month,w=2,l=1)
Returns a multi-line string representing the calendar for a specific month of a given year.

[Link](2025, 10)
Prints the calendar for October 2025 directly on the screen.
It does not return a value — it just displays the calendar.

[Link]()
Returns the current setting for the first day of the week in the calendar module.
In Python’s calendar module, weeks can start on any day (Monday, Sunday, etc.).
By default, the first weekday is Monday (0).
The [Link]() function tells you which day is currently set as the first weekday.
To change it, use [Link](day).

print("Default first weekday:", [Link]())


Output:
Default first weekday: 0

[Link]([Link])
print("Updated first weekday:", [Link]())
Output:
Updated first weekday: 6

[Link](year)
Returns True if the given year is a leap year, otherwise False.
A leap year has 366 days instead of 365.
The extra day (Feb 29) occurs every 4 years, with a few exceptions.

Leap Year Rules


A year is a leap year if:
It is divisible by 4,
But not divisible by 100,
Unless it is also divisible by 400.

Example:
2024 → Leap year
2100 → Not a leap year
2000 → Leap year

print([Link](2024))
Output:
True

[Link](y1,y2)
Returns the number of leap years in the range from y1 to y2, excluding y2.

print([Link](2000, 2025))
Output:7
[Link](year,month)
Returns a matrix (list of lists) representing the calendar of a given month.
Each inner list represents a week, and each day is represented by an integer.
The first weekday depends on [Link]().
(By default, it starts on Monday.)
Days outside the month are represented by 0.
Each week is a list of 7 integers.

month_matrix = [Link](2025, 10)


for week in month_matrix:
print(week)
Output:
[0, 0, 0, 1, 2, 3, 4]
[5, 6, 7, 8, 9, 10, 11]
[12, 13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24, 25]
[26, 27, 28, 29, 30, 31, 0]

[Link](year, month)
Returns a tuple (first_weekday, number_of_days) for the specified month and year.
The first value tells which day of the week the month starts on.
The second value tells how many days are in that month.

Weekdays are numbered as:


0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday,
4 = Friday, 5 = Saturday, 6 = Sunday.

result = [Link](2025, 10)


print(result)
Output:
([Link], 31)

[Link](tupletime)
Converts a time tuple in UTC (Coordinated Universal Time) into a Unix timestamp (seconds
since January 1, 1970).
It is the inverse of [Link]() from the time module.
Useful for converting a structured time (tuple) to seconds since epoch.

import calendar
t = (2025, 10, 31, 12, 0, 0) # 31 Oct 2025, [Link] UTC
timestamp = [Link](t)
print(timestamp)
Output:
1761912000

[Link](year, month, day)


Returns an integer (0–6) representing the day of the week for a given date.
This function helps you find which weekday a specific date falls on.

day_num = [Link](2025, 10, 31)


print(day_num)
Output:
4

[Link]

import calendar
text_cal = [Link](firstweekday = 0)
year = 2018
# Default value of width is 3
# printing formatyear
print(text_cal.formatyear(year))

Python Random Module


Python Random module is an in-built module of Python which is used to generate random
numbers. These are pseudo-random numbers means these are not truly random. This module can
be used to perform random actions such as generating random numbers, print random a value for
a list or string, etc.

Example: Printing a random value from a list


import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
Output: 6

Example: Creating random numbers with seeding value


import random
[Link](5)
print([Link]())
print([Link]())
Output:
0.6229016948897019
0.7417869892607294

Creating Random Integers


[Link]() method is used to generate random integers between the given
range.
Syntax :
randint(start, end)
Example: Creating random integers
# Python3 program explaining work of randint() function
# import random module
import random
# Generates a random number between
# a given positive range
r1 = [Link](5, 15)
print("Random number between 5 and 15 is % s" % (r1))
# Generates a random number between
# two given negative range
r2 = [Link](-10, -2)
print("Random number between -10 and -2 is % d" % (r2))
Output:
Random number between 5 and 15 is 8
Random number between -10 and -2 is -10
Creating Random Floats
[Link]() method is used to generate random floats between 0.0 to 1.
Syntax:
[Link]()
Example:
# program to demonstrate the use of random() function .
import random
# Prints random item
print([Link]())
Output:
0.11320596465314436

Selecting Random Elements


[Link]() function is used to return a random item from a list, tuple, or
string.
Syntax:
[Link](sequence)
Example: Selecting random elements from the list, string, and tuple
# program to demonstrate the use of the choice() method
# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
# prints a random item from the string
string = "python"
print([Link](string))
# prints a random item from the tuple
tuple1 = (1, 2, 3, 4, 5)
print([Link](tuple1))
Output:
4
y
4
Shuffling List
[Link]() method is used to shuffle a sequence (list). Shuffling means
changing the position of the elements of the sequence.
Syntax:
[Link](sequence, function)
Example: Shuffling a List
# import the random module
import random
# declare a list
sample_list = [1, 2, 3, 4, 5]
print("Original list : ")
print(sample_list)
# first shuffle
[Link](sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
[Link](sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
Output:
Original list:
[1, 2, 3, 4, 5]
After the first shuffle :
[4, 3, 5, 2, 1]
After the second shuffle:
[1, 3, 4, 5, 2]

Common questions

Powered by AI

When deciding between using a Python module, package, or a built-in module, several considerations come into play. A built-in module offers pre-packaged, well-tested functions beneficial for standard tasks, ensuring reliability and reducing the need for new code development . A user-defined module suits scenarios requiring customized logic, specific utilities, or when encapsulating frequently reused code to maintain structure and clarity. Opting for a package, which groups multiple modules, is ideal when building large applications needing modular architecture for better maintainability and namespace management . Considerations involve the scope of functionality, reusability requirements, dependency management, and ease of maintenance.

A non-empty __init__.py file in a Python package can define which modules within the package are exposed to the outside world when the package is imported. By specifically importing modules or functions in the __init__.py file, you can control what components of the package are directly accessible. For example, if __init__.py contains 'from .mod1 import greet' and 'from .mod2 import sum', importing the package will only make these functions available directly . This is beneficial for modular code architecture, as it manages namespace clutter and prevents unintended exposure of internal functions or classes.

The datetime.timedelta class in Python is used to represent the difference between two datetime, date, or time instances. It provides an efficient way to perform arithmetic operations on date and time values by representing durations. You can add or subtract a timedelta object from datetime objects to compute future or past dates, effectively managing periods in applications that track events or deadlines . For instance, if you have a task deadline three days from a project's start date, you can determine the deadline date by adding timedelta(days=3) to the start date.

Using 'from module import *' imports all the functions and variables defined in the module into the current namespace. This practice is not recommended because it can lead to naming conflicts; if two modules have functions or variables with the same name, they will conflict and potentially override each other in the namespace . Additionally, it reduces code clarity, as it's not immediately clear which module a particular function or variable is coming from, making maintenance and debugging more difficult.

The time.sleep() method in Python delays the execution of the current script for a specified number of seconds. This is particularly useful in scenarios that require simulation of time passage, handling dependencies or resources that refresh at fixed intervals, or when creating controlled pauses between operations to avoid overwhelming system resources or API rate limits . A practical use case might be spreading out requests to an external service to prevent hitting rate limits, or implementing periodic polling systems where tasks only proceed after waiting intervals.

The seed function of Python's random module initializes the random number generator with a seed value, which influences the sequence of random numbers generated. Setting a seed ensures that the same sequence of numbers can be reproduced across different executions, making the random processes predictable. This determinism is useful for debugging purposes, where consistent results across runs are essential, or when exact steps in research or simulations need replicable results . Without setting a seed, the random number generator would produce different sequences in each run, driven by the system time or other entropy sources.

The datetime module in Python offers several functions for manipulating and presenting date and time information. It can extract individual elements like year, month, day, hour, minute, and second from datetime objects . With datetime.strftime(), it can convert datetime objects to strings using custom formats, useful for display purposes. The module also allows comparison of two datetime objects and calculates differences between them using operators like '<' or by directly subtracting them, resulting in a timedelta object that shows differences in days and time . Additionally, using datetime's methods like isoformat() can present datetime in ISO 8601 format, suitable for standardized data exchange.

To reload a Python module after making changes to its code without restarting the interpreter, you can use the 'importlib.reload()' function. First, import the target module normally with 'import module_name'. After making changes to the module's code, import the importlib module with 'import importlib', and then call 'importlib.reload(module_name)'. This process forces Python to reload the module and update its definitions to reflect the recent changes made in the code .

Python's calendar module provides functions like calendar.monthcalendar() to represent a month as a matrix (list of lists), with each inner list representing a week. This function accounts for the month's day distribution, and days outside the month's range are denoted as zeros . This representation is useful for creating visualizations of a month's layout in applications that require a structured calendar view, such as scheduling apps, resource allocation tools, or when processing information related to specific dates within a month. Furthermore, functions like calendar.monthrange() can be used to determine the first weekday and number of days in a month, which are essential for accurate calendar manipulation and display .

Using an alias when importing a module in Python allows you to assign a different, typically shorter, name to the module. This can make your code more concise and potentially easier to read, especially when the module name is long or frequently used. For example, you can import the math module as 'import math as m', allowing you to use 'm.pi' instead of 'math.pi' to access the pi constant . The main advantage of using an alias is enhanced readability and efficiency when writing code, as it reduces the length of repetitive code lines involving module names.

You might also like