Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Packages _ Datetime Functions & Modules - Notes

Uploaded by

tanwarvaishu9
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)
3 views

Python Packages _ Datetime Functions & Modules - Notes

Uploaded by

tanwarvaishu9
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/ 18

Python Packages | Datetime Functions &

Modules - Notes

Topics Covered:
● Python Packages
● Python Modules
● Datetime Functions in Python

Python Packages

To understand Python packages, we’ll briefly look at scripts and


modules. A “script” is something you execute in the shell to
accomplish a defined task.
A module on the other hand is a Python program that you import,
either in interactive mode or into your other programs. “Module” is really
an umbrella term for reusable code.
A Python package usually consists of several modules. Physically, a
package is a folder containing modules and maybe other folders that
themselves may contain more folders and modules.

It consists of several modules which in turn may contain several classes,


functions, variables. It is a folder that contains various modules as files.

Importing a Python Package

Syntax:-
import <package_name>

Import Modules from a Package

Syntax:-
import <package_name>.<module_name>

1
Install New Package

The official repository for finding and downloading such third-party


packages is the Python Package Index, usually referred to simply as
PyPI.

To install packages from PyPI, use the package installer pip

Syntax :

Pip install <package_name>

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.
As our program grows bigger, it may contain many lines of code.
Instead of putting everything in a single file, we can use modules to
separate codes in separate files as per their functionality. This makes our
code organized and easier to maintain.
Module is a file that contains code to perform a specific task. A
module may contain variables, functions, classes etc.

Import modules in Python

We can import the definitions inside a module to another module or the


interactive interpreter in Python. Below are different ways of importing
a module.

We use the import keyword to do this.

2
Python import with Renaming

In Python, we can also import a module by renaming it.

Example:-

Output:-

Here, We have renamed the math module as m. This can save us typing
time in some cases.

Note:- The name math is not recognized in our scope. Hence, math.pi is
invalid, and m.pi is the correct implementation.

Python from...import statement

We can import specific names from a module without importing the


module as a whole.

Example:-

Output:-

Here, we imported only the pi attribute from the math module.

3
Import all names
In Python, we can import all names(definitions) from a module using
the following construct:

Example:-

Output:-

Here, we have imported all the definitions from the math module. This
includes all names visible in our scope except those beginning with an
underscore(private definitions).

Importing everything with the asterisk (*) symbol is not a good


programming practice. This can lead to duplicate definitions for an
identifier. It also hampers the readability of our code.

Python Math Module

Python provides the math module to deal with calculations that include
financial or scientific operations. It includes basic as well as advance
operations such as addition(+), subtraction(-), multiplication(*),
division(/) and trigonometric, logarithmic, exponential functions.

Constants Provided:
● Euler’s Number: math.e
● Pi: math.pi
● Tau: math.tau
● Infinity: math.inf
● Not a Number (NaN): math.nan

4
Math methods:

● math.ceil(): Rounds a number up to the nearest integer


● math.comb(): Returns the number of ways to choose k items from
n items without repetition and order
● math.degrees(): Converts an angle from radians to degrees
● math.dist(): Returns the Euclidean distance between two points
(p and q), where p and q are the coordinates of that point
● math.exp(): Returns E raised to the power of x
● math.factorial(): Returns the factorial of a number
● math.floor(): Rounds a number down to the nearest integer
● math.fsum(): Returns the sum of all items in any iterable (tuples,
arrays, lists, etc.)
● math.gcd(): Returns the greatest common divisor of two integers
● math.log(): Returns the natural logarithm of a number, or the
logarithm of number to base
● math.log10(): Returns the base-10 logarithm of x
● math.log1p(): Returns the natural logarithm of 1+x
● math.log2(): Returns the base-2 logarithm of x
● math.perm(): Returns the number of ways to choose k items from
n items with order and without repetition
● math.pow(): Returns the value of x to the power of y
● math.prod(): Returns the product of all the elements in an iterable
● math.radians(): Converts a degree value into radians
● math.sqrt(): Returns the square root of a number

Random

It is used for generation of random numbers. They are not entirely


random, rather are pseudo random numbers.

5
Random Methods:

● seed(): Initialize the random number generator


● getstate(): Returns the current internal state of the random
number generator
● setstate(): Restores the internal state of the random number
generator
● randrange(): Returns a random number between the given range
● randint(): Returns a random number between the given range
● choice(): Returns a random element from the given sequence
● choices(): Returns a list with a random selection from the given
sequence
● shuffle(): Takes a sequence and returns the sequence in a
random order
● sample(): Returns a given sample of a sequence
● random(): Returns a random float number between 0 and 1
● uniform(): Returns a random float number between two given
parameters

Collections Library

We have already studied the four collection data types- list, tuples,
sets and dictionary. Other than them, Python also has a builtin
module called as Collection. It has different types of containers which
are objects used to store different objects and provide a way to
access them and iterate over them.

Counters: It is a subclass of dictionary which is used to count hashable


objects. It is used to keep the count of the elements in an iterable in the
form of an unordered dictionary where the key represents the element
in the iterable and value represents the count of that element in the
iterable.

6
Example:-

Output:-

OrderedDict: An OrderedDict is also a subclass of dictionary but unlike


dictionary, it remembers the order in which the keys were inserted.Even
if we change the value of the key, the position will not be changed
because of the order in which it was inserted in the dictionary.

Example:-

Output:-

Deque: Deque (Doubly Ended Queue) is the optimized list to perform


insertion and deletion easily from both sides of the container.

7
Example:-

Output:-

namedtuple( ): It returns a tuple with a named entry, which means


there will be a name assigned to each value in the tuple. It overcomes
the problem of accessing the elements using the index values. It
becomes easier to access the values, since we do not have to remember
the index values to get specific elements.

Example:-

8
Output:-

Python Itertools

It contains various functions that work on iterators to produce complex


iterators. This module works as a fast, memory-efficient tool that is used
either by themselves or in combination to form iterator algebra.

Combinatoric Iterators

Product(): It is used to compute the cartesian product. To calculate the


product with itself, repeat keyword is used which specifies the number
of repetitions.

Example:-

9
Output:-

Permutations(): It used to generate all possible permutations of an


iterable.

Example:-

Output:-

10
Combinations(): It prints all the possible combinations (without
replacement).

Example:-

Output:-

11
Combinations_with_replacement(): It returns a subsequence of length
n from the elements of the iterable where n is the argument that
determines the length of the subsequences generated by it. Individual
elements may repeat itself in combinations_with_replacement
function.

Example:-

Output:-

12
Datetime Functions in Python

In python, a module called the Datetime module is available which


works with real date and times. Date is not a data type in python but
we can work by importing modules named datetime, time, and
calendar.

Importing a Python Package

Syntax:-
import datetime as dt

# import datetime library with dt as the alias name

The datetime classes are classified in the six main classes:

● date - It consists of the year, month, and day as attributes.


● 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.
● datetime - It is a grouping of date and time, along with the
attributes year, month, day, hour, minute, second, microsecond,
and tzinfo.
● timedelta - It represents the difference between two dates, time or
datetime instances to microsecond resolution.
● tzinfo - It provides time zone information objects.
● timezone - It is included in the new version of Python. It is the
class that implements the tzinfo abstract base class.

13
To get current time:

Example:-

Output:-

14
To compare two dates:

Example:-

Output:-

To print the calendar for December 2022:

Example:-

15
Addition and Subtraction of date and time

What is the date and time 5 days, 3 hours, 45 minutes and 45 sec
ahead from now?

Example:-

Output:-

What is the date and time 1 week and 3 days before 2019 June 1, 9 AM?

Example:-

16
Output:-

Calculate the difference between two dates

Example:-

Output:-

Date Parsing formats

● %Y - Year (in YYYY format) - eg 2021


● %y - Year (in YY format) - eg - 21
● %B - Month(full name - March)
● %b - Month(three letters of the month- Mar)
● %A - Weekday full name (Thursday)
● %a - Weekday Short name (Thu)
● %d - Day of month(1-31)
● %w - weekday number (0-Sun, 6-Sat)
● %m - month(01-Jan, 12-Dec)
● %H - Hour
● %M - Minute
● %S - Second

17
strftime() Method
The method strftime(), takes one parameter, format, to specify the
format of the returned string

Example:-

Output:-

strptime() Method

This function takes two arguments, a string in which some time is given
and a format code, to change the string into, the string is changed to
the DateTime object

Example:-

Output:-

Reference Notebooks

● Reference Jupyter Notebook

18

You might also like