- Built-in Modules
- Import statement
- Packages
- Date and Time Module
Python Module
A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
Example
In this example, we will create a module named as file.py which contains a function func that contains a code to print some message on the console.
Let’s create the module named as file.py.
1.#displayMsg prints a message to the name being passed.
2.def displayMsg(name)
3. print(“Hi “+name);
Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.
1. The import statement
2. The from-import statement
The import statement
The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file.
The syntax to use the import statement is given below.
1. import module1,module2,…….. module n
Hence, if we need to call the function displayMsg() defined in the file file.py, we have to import that file as a module into our module as shown in the example below.
Example:
1. import file;
2. name = input(“Enter the name?”)
3. file.displayMsg(name)
Output:
Enter the name?John
Hi John
The from-import statement
Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from? import statement. The syntax to use the from-import statement is given below.
1.from < module-name> import <name 1>, <name 2>..,<name n>
Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.
calculation.py:
1. #place the code in the calculation.py
2. def summation(a,b):
3. return a+b
4. def multiplication(a,b):
5. return a*b;
6. def divide(a,b):
7. return a/b;
Main.py:
1. from calculation import summation
2. #it will import only the summation() from calculation.py
3. a = int(input(“Enter the first number”))
4. b = int(input(“Enter the second number”))
5. print(“Sum = “,summation(a,b)) #we do not need to specify the module name while accessing summation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from…import statement is always better to use if we know the attributes to be imported from the module in advance. It doesn’t let our code to be heavier. We can also import all the attributes from a module by using *.
Consider the following syntax.
1. from <module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.
The syntax to rename a module is given below.
1.import <module-name> as <specific-name>
Example
1. #the module calculation of previous example is imported in this example as cal.
2. import calculation as cal;
3. a = int(input(“Enter a?”));
4. b = int(input(“Enter b?”));
5. print(“Sum = “,cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
Using dir() function
The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and functions defined in this module.
Consider the following example.
Example
1. import json
3. List = dir(json)
5. print(List)
Output:
[‘JSONDecoder’, ‘JSONEncoder’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’,
‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__path__’, ‘__spec__’, ‘__version__’,
‘_default_decoder’, ‘_default_encoder’, ‘decoder’, ‘dump’, ‘dumps’, ‘encoder’, ‘load’, ‘loads’, ‘scanner’]
The reload() function
As we have already stated that, a module is loaded once regardless of the number of times it is imported into the python source file. However, if you want to reload the already imported module to re-execute the top-level code, python provides us the reload() function. The syntax to use the reload() function is given below.
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we must use the following line of code.
1. reload(calculation)
Python packages
The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the application level code efficiently.
Let’s create a package named Employees in your home directory. Consider the following steps.
1.Create a directory with name Employees on path /home.
2.Create a python source file with name ITEmployees.py on the path /home/Employees.
ITEmployees.py
1. def getITNames():
2. List = [“John”, “David”, “Nick”, “Martin”]
3. return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a function getBPONames().
4.Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a package, we need to include one more file here, that is __init__.py which contains the import statements of the modules defined in this directory.
__init__.py
1. from ITEmployees import getITNames
2. from BPOEmployees import getBPONames
5.Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have to create __init__.py inside a directory to convert this directory to a package.
6.To use the modules defined inside the package Employees, we must have to import this in our python source file. Let’s create a simple python source file at our home directory (/home) which uses the modules defined in this package.
Test.py
1. import Employees
2. print(Employees.getNames())
Output:
[‘John’, ‘David’, ‘Nick’, ‘Martin’]
We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application requirements.
The following image shows the directory structure of an application Library management system which contains three sub-packages as Admin, Librarian, and Student. The sub-packages contain the python modules.
Python datetime
Python provides the datetime module 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 timing.
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.
Example1-Get Current date & Time
import datetime
cdtime = datetime.datetime.now()
print(cdtime)
Output:
2020-09-01 10:18:36.461122
we have imported datetime module using import datetime statement.
One of the classes defined in the datetime module is datetime class. We then used now() method to create a datetime object containing the current local date and time.
Example2-Get Current date
import datetime
date1 = datetime.date.today()
print(date1)
Output:
2020-09-01
In this program, we have used today() method defined in the date class to get a date object containing the current local date.
Commonly used classes in the datetime module are:
•date Class
•time Class
•datetime Class
•timedelta Class
datetime.date Class
You can instantiate date objects from the date class. A date object represents a date (year, month and day).
Example 3: Date object to represent a date
import datetime
d = datetime.date(2020, 1, 7)
print(d)
Output:
2020-01-07
We can only import date class from the datetime module. Here’s how:
from datetime import date
a = date(2020, 4, 13)
print(a)
Output:
2020-04-13
Python datetime Contd..
Example: Print today’s year, month and day
We can get year, month, day, day of the week etc. from the date object easily.
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: 2020
Current month: 9
Current day: 1
Example : Print hour, minute, second and microsecond
time object, you can easily print its attributes such as hour, minute etc.
from datetime import time
a = time(11, 34, 56)
print(“hour =”, a.hour)
print(“minute =”, a.minute)
print(“second =”, a.second)
print(“microsecond =”, a.microsecond)
Output:
hour = 11
minute = 34
second = 56
microsecond = 0
The calendar module
Python provides a calendar object that contains various methods to work with the calendars.
Example: Print the calendar for the month August-2020.
import calendar
cal = calendar.month(2020,8)
#printing the calendar of August 2020
print(cal)
Output:
Example : Print the calendar of year2020
import calendar
#printing the calendar of the year 2020
s = calendar.prcal(2020)