In this article MODULES in python we give the information about “Modules” in Python are files that contain Python code. It can contain functions, classes, and variables, and you can use them in your scripts. It help to reuse code and keep the project organized.
MODULES in python:
“Modules” in Python are files that contain Python code. It can contain functions, classes, and variables, and you can use them in your scripts. It help to reuse code and keep the project organized.
Types of Python modules
- Built-in Modules
These are already available in Python. Example:
- math
- os
- random
- sys
- User-defined Modules
These modules are created by the user. For example, if you write functions and code in a file and use it in another program, it becomes your user-defined module.
import statement to use the module
import is used to access a module in Python.
Example: built-in module
import math
print(math.sqrt(16)) # Output: 4.0
Example: User-Defined Module
Suppose, you have a file my_module.py which contains this code:
# my_module.py
def greet(name):
return f”Hello, {name}!”
Now you can import it into your script like this:
import my_module
print(my_module.greet(“Rajveer”)) # Output: Hello, Rajveer!
Using from … import
You can also import just a specific function or variable from a module:
from math import sqrt
print(sqrt(25)) # Output: 5.0
Benefits of Python modules
- Code Reusability: Code written once can be used again and again.
- Organized Code: Dividing the code into separate files makes it easier to read and understand.
- Use of built-in tools: The work can be made simpler and faster with the built-in modules available in Python.
Datetime module:
Python’s datetime module is used to manage time and date. It simplifies timestamps, dates, times, and time calculations.
Below the main parts of datetime module and their usage:
using datetime module
Importing the datetime module:
import datetime
- Getting the current date and time
Example:
import datetime
# Current date and time
current_datetime = datetime.datetime.now()
print(“Current date and time:”, current_datetime)
Output:
Current date and time: 2024-12-17 12:34:56.789012
- Getting only the date
Example:
import datetime
# today’s date
current_date = datetime.date.today()
print(“Today’s date:”, current_date)
Output:
Today’s date: 2024-12-17
- Setting custom date and time
You can set your own date and time.
Example:
import datetime
# Custom date and time
custom_datetime = datetime.datetime(2024, 12, 25, 10, 30, 45)
print(“Custom date and time:”, custom_datetime)
Output:
Custom date and time: 2024-12-25 10:30:45
- Extracting separate parts of date and time
Example:
import datetime
now = datetime.datetime.now()
print(“Year:”, now.year)
print(“Month:”, now.month)
print(“Day:”, now.day)
print(“hour:”, now.hour)
print(“minute:”, now.minute)
print(“Second:”, now.second)
- Date and Time Difference
You can find the time difference by using timedelta.
Example:
import datetime
# today’s date
today = datetime.date.today()
# custom date
future_date = datetime.date(2024, 12, 25)
# find the difference
difference = future_date – today
print(“Difference:”, difference.days, “days”)
Output:
Gap: 8 days
- Formatting the date and time
use of strftime
You can format the date and time as per your choice.
Example:
import datetime
now = datetime.datetime.now()
formatted_date = now.strftime(“%d-%m-%Y %H:%M:%S”)
print(“Formatted date and time:”, formatted_date)
Formatting Codes:
code meaning
%d days (01-31)
%m month (01-12)
%Y Year (four digits)
%H Hours (in 24-hour format)
%M minutes
%S seconds
- Parsing Strings
Using strptime:
Example:
import datetime
date_str = “25-12-2024”
parsed_date = datetime.datetime.strptime(date_str, “%d-%m-%Y”)
print(“Parsed Date:”, parsed_date)
- Time Handling
Getting time only:
import datetime
# time only
time_now = datetime.datetime.now().time()
print(“Current time:”, time_now)
9.UTC Time
Example:
import datetime
utc_now = datetime.datetime.utcnow()
print(“Current UTC time:”, utc_now)
Main class of datetime module:
class use
date Working only with dates
time working only with time
datetime Working with date and time
timedelta for time interval
Calendar modules:
The calendar module in Python is used to perform calendar related tasks. With the help of this module you can create calendars, calculate dates and days, and get information about the year or month.
Using the calendar module
First you need to import the module:
import calendar
- Show month calendar
Example:
import calendar
# Show calendar of any month
print(calendar.month(2024, 12)) # Calendar for December 2024
Output:
December 2024
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
- Show full year calendar
Example:
import calendar
# whole year calendar
print(calendar.calendar(2024))
- Getting information about any day
weekday()
Returns the day of a date (0=Monday, 6=Sunday).
import calendar
day = calendar.weekday(2024, 12, 25) # 25 December 2024
print(“Day:”, day) # Output: 2 (Wednesday)
- First and last day of the year
monthrange()
This function tells the start day of the month and the total days in the month.
import calendar
start_day, total_days = calendar.monthrange(2024, 12)
print(“First day:”, start_day) # Output: 6 (Sunday)
print(“Total days:”, total_days) # Output: 31
-
Checking leap years
isleap()
This function tells whether a year is a leap year or not.
import calendar
print(calendar.isleap(2024)) # Output: True (leap year)
print(calendar.isleap(2023)) # Output: False
- Counting leap years between two years
leapdays()
This function tells the number of leap years that come between two years.
import calendar
leap_years = calendar.leapdays(2000, 2025) # between 2000 and 2025
print(“Number of leap years:”, leap_years) # Output: 6
- Creating a calendar in custom format
Example:
import calendar
# HTML calendar
html_cal = calendar.HTMLCalendar().formatmonth(2024, 12)
print(html_cal)
- Getting the calendar in the loop
monthcalendar()
It gives the month calendar in the form of a 2D list.
Example:
import calendar
month = calendar.monthcalendar(2024, 12)
for week in month:
print(week)
Output:
[0, 0, 0, 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, 0, 0, 0, 0]
- Set a custom start day of the week
By default, Monday is considered the first day of the week in Python. You can change this.
Example:
import calendar
# Setting the first day of the week to Sunday
calendar.setfirstweekday(calendar.SUNDAY)
# show calendar
print(calendar.month(2024, 12))
Main functions of calendar module
Function Description
calendar(year) prints the calendar for the entire year
month(year, month) prints the calendar for a month
isleap(year) Checks whether the year is a leap year or not
leapdays(y1, y2) returns the number of leap years between two years.
monthrange(year, month) returns the first day of the month and the total days
weekday(y, m, d) returns the day of a date
math module in python
Python’s math module is used to make mathematical calculations simpler and faster. It comes with a host of pre-built functions that allow you to perform advanced calculations, trigonometry, logarithms, and other mathematical operations with ease.
using the math module
Importing the math module:
import math
Main functions of math module
- Basic Mathematical Functions
function description example
math.ceil(x) Rounds the number upward math.ceil(4.2) → 5
math.floor(x) rounds the number down math.floor(4.8) → 4
math.fabs(x) gives the magnitude of the number math.fabs(-5) → 5.0
math.factorial(x) gives the factorial of the number math.factorial(5) → 120
math.gcd(a, b) Greatest Common Factor (GCD) of two numbers math.gcd(12, 18) → 6
- Exponential and Logarithm Functions
function description example
math.exp(x) calculates e^x math.exp(2) → 7.389
math.log(x, base) Finds the logarithm (base is optional) math.log(8, 2) → 3.0
math.log10(x) Finds the logarithm of base 10 math.log10(100) → 2.0
math.pow(x, y) finds x to the power y math.pow(2, 3) → 8.0
math.sqrt(x) finds the square root math.sqrt(16) → 4.0
-
Trigonometry Functions
function description example
math.sin(x) sine of angle in radians math.sin(math.pi/2) → 1.0
math.cos(x) cosine of angle in radians math.cos(0) → 1.0
math.tan(x) Tangent of angle in radians math.tan(math.pi/4) → 1.0
math.asin(x) inverse sine math.asin(1) → 1.5708
math.acos(x) inverse cosine math.acos(1) → 0.0
math.atan(x) inverse tangent math.atan(1) → 0.7854
math.degrees(x) converts radians to degrees math.degrees(math.pi) → 180.0
math.radians(x) converts degrees to radians math.radians(180) → 3.14159
- Float and Fraction Functions
function description example
math.modf(x) returns decimal and integer parts of the number math.modf(4.5) → (0.5, 4.0)
math.trunc(x) returns integer division of a number math.trunc(4.9) → 4
- Special Functions
function description example
math.pi Value of π (pi) math.pi → 3.141592653589793
math.e Value of e (Natural Logarithm Base) math.e → 2.718281828459045
math.inf Value of Infinity math.inf → ∞
math.nan Value of NaN (Not a Number) math.nan → NaN
Some useful examples of math module
Example 1: to calculate
import math
radius = 5
area = math.pi * math.pow(radius, 2)
print(“Area of circle:”, area) # Output: 78.53981633974483
Example 2: Trigonometry
import math
angle = 45 # in degrees
radian = math.radians(angle)
print(“Sine:”, math.sin(radian)) # Output: 0.7071067811865476
print(“Cosine:”, math.cos(radian)) # Output: 0.7071067811865476
print(“Tangent:”, math.tan(radian)) # Output: 1.0
Example 3: Factorial and GCD
import math
print(“Factorial of 5:”, math.factorial(5)) # Output: 120
print(“GCD of 12 and 18:”, math.gcd(12, 18)) # Output: 6
Example 4: Square Roots and Logarithms
import math
print(“Square root of 16:”, math.sqrt(16)) # Output: 4.0
print(“Logarithm of base 10:”, math.log10(100)) # Output: 2.0
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining