[Go to site: main page, start]

0% found this document useful (0 votes)
22 views12 pages

Python Calendar Module Overview

The document provides an overview of Python modules, explaining their definition, usage, and how to import them using different statements. It covers the creation of modules, the use of packages, and the datetime module for handling date and time operations. Additionally, it discusses variable scope, the dir() and reload() functions, and the calendar module for printing calendars.

Uploaded by

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

Python Calendar Module Overview

The document provides an overview of Python modules, explaining their definition, usage, and how to import them using different statements. It covers the creation of modules, the use of packages, and the datetime module for handling date and time operations. Additionally, it discusses variable scope, the dir() and reload() functions, and the calendar module for printing calendars.

Uploaded by

sourav.me.klc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Modules

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 [Link] which contains a function func that
contains a code to print some message on the console.

Let's create the module named as [Link].

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 [Link], 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. [Link](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.

[Link]:

#place the code in the [Link]


def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

[Link]:

from calculation import summation


#it will import only the summation() from [Link]
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while acce
ssing 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 = ",[Link](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
2.
3. List = dir(json)
4.
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)

Scope of variables
In Python, variables are associated with two types of scopes. All the variables defined in a
module contain the global scope unless or until it is defined within a function.

All the variables defined inside a function contain a local scope that is limited to this function
itself. We can not access a local variable globally.

If two variables are defined with the same name with the two different scopes, i.e., local and
global, then the priority will always be given to the local variable.

Consider the following example.

Example

1. name = "john"
2. def print_name(name):
3. print("Hi",name) #prints the name that is local to this function only.
4. name = input("Enter the name?")
5. print_name(name)

Output:

Hi David

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 [Link] on the path /home/Employees.

[Link]

1. def getITNames():
2. List = ["John", "David", "Nick", "Martin"]
3. return List;

3. Similarly, create one more python file with name [Link] 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.

[Link]

1. import Employees
2. print([Link]())

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 Date and time


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.

In this section of the tutorial, we will discuss how to work with the date and time objects in
Python.

The datetime classes are classified in the six main classes.


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.

Consider the following example

import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print([Link]())

Output:

1585928913.6519969

How to get the current time?


The localtime() functions of the time module are used to get the current time tuple. Consider
the following example.

Example

import time;

#returns a time tuple

print([Link]([Link]()))

Output:
time.struct_time(tm_year=2020, tm_mon=4, tm_mday=3, tm_hour=21, tm_min=21, tm_sec=40, tm_wday=4,
tm_yday=94, tm_isdst=0)

Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.

Index Attribute Values

0 Year 4 digit (for example 2018)

1 Month 1 to 12

2 Day 1 to 31

3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 60

6 Day of weak 0 to 6

7 Day of year 1 to 366

8 Daylight savings -1, 0, 1 , or -1

Getting formatted time


The time can be formatted by using the asctime() function of the time module. It returns the
formatted time for the time tuple being passed.

Example

import time
#returns the formatted time

print([Link]([Link]([Link]())))

Output:

Tue Dec 18 15:31:39 2018

Python sleep time


The sleep() method of time module is used to stop the execution of the script for a given
amount of time. The output will be delayed for the number of seconds provided as the float.

Consider the following example.

Example

import time
for i in range(0,5):
print(i)
#Each element will be printed after 1 second
[Link](1)

Output:

0
1
2
3
4

The datetime Module


The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.

To work with dates as date objects, we have to import the datetime module into the python
source code.

Consider the following example to get the datetime object representation for the current
time.

Example

import datetime
#returns the current datetime object
print([Link]())

Output:

2020-04-04 13:18:35.252578

Creating date objects


We can create the date objects bypassing the desired date in the datetime constructor for
which the date objects are to be created.
Consider the following example.

Example

1. import datetime
2. #returns the datetime object for the specified date
3. print([Link](2020,04,04))

Output:

2020-04-04 00:00:00

We can also specify the time along with the date to create the datetime object. Consider the
following example.

Example

1. import datetime
2.
3. #returns the datetime object for the specified time
4.
5. print([Link](2020,4,4,1,26,40))

Output:

2020-04-04 01:26:40

In the above code, we have passed in datetime() function year, month, day, hour, minute, and
millisecond attributes in a sequential manner.

Comparison of two dates


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

Consider the following example.

Example

1. from datetime import datetime as dt


2. #Compares the time. If the time is in between 8AM and 4PM, then it prints working h
ours otherwise it prints fun hours
3. if dt([Link]().year,[Link]().month,[Link]().day,8)<[Link]()<dt([Link]().year,[Link]
().month,[Link]().day,16):
4. print("Working hours....")
5. else:
6. print("fun hours")

Output:

fun hours

The calendar module


Python provides a calendar object that contains various methods to work with the calendars.

Consider the following example to print the calendar for the last month of 2018.

Example

import calendar;
cal = [Link](2023,11)
#printing the calendar of December 2018
print(cal)

Output:

March 2020
Mo Tu We Th Fr Sa Su
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

Printing the calendar of whole year


The prcal() method of calendar module is used to print the calendar of the entire year. The
year of which the calendar is to be printed must be passed into this method.

Example

import calendar
#printing the calendar of the year 2019
s = [Link](2023)

Output:

Common questions

Powered by AI

The Python 'datetime' module is used extensively for working with dates and times in applications. It offers six main classes: 'date' for representing ideal calendar dates, 'time' for recording precise times, 'datetime' for all-in-one date and time records, 'timedelta' for differences between dates or times, 'tzinfo' for managing time zone information, and 'timezone', which extends 'tzinfo' for fixed-offset time zones . These classes enable the creation and manipulation of date-time objects, comparison of dates, and scheduling based on time, making it versatile for handling various time-related operations in programming .

The 'dir()' function in Python provides a sorted list of names defined in a passed module, which includes sub-modules, variables, and functions. This aids in understanding the available functionalities within a module without directly inspecting the source code . On the other hand, the 'reload()' function is utilized to reload an already imported module, forcing the re-execution of its top-level code. This is particularly useful during development to reflect recent code changes without restarting the entire application environment .

In Python's 'datetime' module, naive datetime objects do not contain enough information to be unambiguous across all contexts, as they do not contain timezone data . They are useful for general time calculations and operations where timezone is not a factor. In contrast, aware datetime objects account for timezone by storing sufficient data to unambiguously locate themselves relative to UTC . They are essential in applications dealing with real-world time that consider daylight saving time or interact across different time zones, as they enable precise and accurate time comparisons and conversions .

The 'import' statement in Python is used to import all the functionality of one module into another, making all the functions and classes available in the module accessible through the module's namespace . In contrast, the 'from-import' statement allows specific attributes or functions of a module to be imported into the current namespace, which can lead to more concise code by eliminating the need to prefix module names to access imported functions . Using 'from-import' is generally more efficient for situations where specific parts of a module are needed, as it avoids loading unnecessary parts of a module and thus can help keep the codebase lighter .

In Python, variables defined in a module generally have a global scope and can be accessed throughout the module unless they are defined within a function, wherein they have a local scope. Variables in local scope are limited to the function itself and not accessible globally . When a variable is defined with the same name in both the local and global scopes, the local scope takes precedence within the function, meaning the local definition will be used over the global one when the function executes .

The '__init__.py' file plays a crucial role in Python packaging by indicating that the directory it resides in should be treated as a package. This transforms a simple directory containing Python files into a package by allowing the inclusion of initialization code or imports for the package level, thereby establishing the package's namespace . In the absence of '__init__.py', a directory would not be treated as a package by Python. This file can also include import statements for sub-modules, making them available at the package level .

The 'sleep()' method from Python's 'time' module is useful in scenarios where a pause or delay is required between operations, such as in automation scripts to manage execution timing, or control processing intervals between repeated tasks . It functions by suspending the execution of the script for a specified number of seconds provided as a float, making it versatile for both short and longer pauses, as demonstrated by inserting a one-second delay in a loop with 'time.sleep(1)' to stagger the printing of numbers .

The Python 'calendar' module offers functions to generate and display a formatted calendar representation for both specific months and entire years. To print a calendar for a particular month, the 'month' method can be used, as demonstrated by calling 'calendar.month(2023, 11)' to print the November 2023 calendar . For a full year's calendar, the 'prcal()' method is used, which takes the year as an argument to output the entire year's calendar, as shown by 'calendar.prcal(2023)' . These functions facilitate easy and formatted visualization of calendars within Python applications.

Renaming a Python module during the import process allows a developer to use an alias that might be shorter, more intuitive, or avoids naming conflicts with other modules. The process involves using the 'as' keyword during import, such as 'import calculation as cal', which allows functions within the calculation module to be called using the alias 'cal' instead . This flexibility is particularly useful in large programs to keep the codebase organized and easily readable, especially when dealing with modules having lengthy or unintuitive names .

Using packages in Python offers several advantages for application development. Packages provide a hierarchical directory structure that helps organize modules logically and categorically, facilitating easier management and scalability of the codebase . They allow developers to create a structured application development environment by including sub-packages and modules, which further organizes code into smaller, manageable segments. This organization is particularly beneficial for large projects where segmented development and teamwork are essential .

You might also like