You are on page 1of 58

Sets in Python

• A Python set is the collection of the unordered items.


Each element in the set must be unique, immutable
(integer, String, float, tuple,etc), and the sets remove
the duplicate elements.
• Sets are mutable which means we can modify it after
its creation.
• Unlike other collections in Python, there is no index
attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index.
However, we can print them all together, or we can
get the list of elements by looping through the set.
Properties of sets in Python.

• Sets in Python are usually used to perform


some mathematical functions such as union,
intersection, difference and complement etc.
• Elements don’t have a specific order.
• Sets can’t have duplicates. Each item is
unique.
• Sets allow addition and deletion operations.
Creating a set

• The set can be created by enclosing the comma-


separated immutable items with the curly braces {}.
• Creation of Set:
– Days = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
– a={1,3,2}
– c={1,2.0,'three'}
Creating Set’s:

 A set doesn't store duplicate objects.


 Even if an object is added more than once inside the curly brackets,
only one copy is held in the set object. Hence, indexing and slicing
operations cannot be done on a set object.
 Example:
>>> S1={1, 2, 2, 3, 4, 4, 5, 5}
>>> S1
{1, 2, 3, 4, 5}
set() function :
• Python also provides the set() method, which can be
used to create the set by the passed sequence.
• Examples:
>>>Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "S
unday"])
>>> s1=set("Python") {'t', 'h', 'o', 'n', 'P', 'y'}
>>> s1
>>> s2=set([45,67,87,36, 55]) {67, 36, 45, 87, 55}
>>> s2
>>> s3=set((10,25,15)) {25, 10, 15}
>>> s3
>>> s4=set(range(1,3)) {1,2}

The order of elements in the set is not necessarily the same as


the order given at the time of assignment. Python optimizes the
structure of a set for performing operations over it, as defined in
mathematics.
Even though immutable objects are stored in a set, the set itself
is a mutable object.

• Only immutable objects can be a part of a set object.


Numbers (integer, float, as well as complex), strings, and
tuple objects are accepted, but list and dictionary objects
are not.
>>> S1={(10,10), 10,20} {10, 20, (10, 10)}
>>> S1

TypeError: unhashable type: 'list'


>>> S2={[10,10], 10,20}
Iterating over Python Set
Days = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Deleting values in Set :
• A set elements don’t have indices, it means we can’t delete an
element using its index.
• We Can use below methods to delete/remove a element from
set.
• Example:
>>> numbers={3,2,1,4,6,5} {1, 2, 3, 4, 5, 6}
>>> numbers

1.discard() :
This method takes the item to delete as an argument.

>>> numbers.discard(3) {1, 2, 4, 5, 6}


>>> numbers
2. remove() :
•Like the discard() method, remove() deletes an item
from the set.
>>> numbers.remove(5)
>>> numbers {1, 2, 4, 6}

>>> numbers.discard(7) {1, 2, 4, 6}


>>> numbers

>>> numbers.remove(7) If you try deleting an


Traceback (most recent call last): item that doesn’t exist
File “<pyshell#37>”, line 1, in <module> in the set, discard()
ignores it, but remove()
numbers.remove(7)
raises a KeyError.
KeyError: 7
3. pop()
• You can call the pop() method on a set.
– it does not take an argument.
– Hence, it pops out an arbitrary item.
– Furthermore, it prints out the item that was popped.
• Example:
>>> numbers.pop() 1

Let’s try popping another element.


>>> numbers.pop() 2
4. clear() :

• The clear() method empties the set in Python.

>>> numbers.clear() set()


>>> numbers

• It denots an empty set as set(), not as set{}.


Updating Sets :

• We use two methods for updating a set- add() and update().


1. add() :
– It takes as argument the item to be added to the set.
>>> numbers={3,1,2,4,6,5}
>>> numbers.add(3.5)
{1, 2, 3, 4, 5, 6, 3.5}
>>> numbers

• If you add an existing item in the set, the set remains


unaffected.
>>> numbers.add(4) {1, 2, 3, 4, 5, 6, 3.5}
>>> numbers
2. update() :

• This method can add multiple items to the set at


once, which it takes as arguments.
>>> numbers.update([7,8],{1,2,9})
>>> numbers

{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9}

Note: We can provide a list, set, strings, and tuples as


arguments.
This is because this is different than creating a set.
Basic Set Operations :

• The set type in Python implements as the set defined


in mathematics.
• Various set operations can be performed.
• Operators “|”, “&”, “-” and “^” perform union,
intersection, difference and symmetric difference
operations, respectively.
• Each of these operators has a corresponding method
associated with the built-in set class like union(),
intersection(), difference(), symmetric_difference().
Union:
• This method performs the union operation on two
or more Python sets.
• It returns all the items that are in any of those sets.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}

>>> s1|s2 {1, 2, 3, 4, 5, 6, 7, 8}

>>> s2.union(s1) {1, 2, 3, 4, 5, 6, 7, 8}


>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set1.union(set2,set3)
{1, 2, 3, 4, 5, 6, 7}
2. Intersection:

• This method takes as argument sets, and returns


the common items in all the sets.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
{4, 5}
>>> s1&s2

{4, 5}
>>> s1.intersection(s2)

>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set2.intersection(set1,set3) set()
3. Difference:

• The difference operation returns the difference of


two or more sets. It returns as a set.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1-s2 {1, 2, 3}
>>> s1.difference(s2)

>>> s2-s1 {8, 6, 7}


>>> s2.difference(s1)

>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7} {1, 2}


>>> set1.difference(set2,set3)
4. Symmetric Difference:
• The result of symmetric difference is a set consisting of
elements in both sets, excluding the common elements.

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1^s2
{1, 2, 3, 6, 7, 8}
>>> s2^s1
>>> s1.symmetric_difference(s2)
>>> s2.symmetric_difference(s1)
Membership :
• We can apply the ‘in’ and ‘not in’ python operators on items
for a set. This tells us whether they belong to the set.
>>> 'p' in {'a','p','p','l','e'}
>>> 0 not in {'0','1'} True
• Deleting a set :
• The del keyword will delete the set completely.
>>> myset = {"apple", "banana", "cherry"}
>>> del myset
>>> myset
Traceback (most recent call last): File "", line 1, in
NameError: name ‘myset’ is not defined
Built-in Set Functions
• Consider set a = {6, 1, 3, 2}
Built-in Function Description Example
Returns True if all elements of the set are >>> all(a)
all()
true (or if the set is empty) True
Returns True if any element of the set is >>> any(a)
any() True
true. If the set is empty, returns False.
Returns the length (number of items) of >>> len(a)
len()
the set. 4
>>> max(a)
max() Returns the maximum element in the set.
6
>>> min(a)
min() Returns the minimum element in the set.
1
Returns a new sorted list from the >>> sorted(a)
sorted() elements in the set (does not sort the set [1, 2, 3, 6]
itself).
Returns the sum of all elements in the set. >>> sum(a)
sum()
(Not applicable to strings) 12
Methods of Sets
Method Description Example
>>> set1={1,2,3}
intersection(), does not update the set on >>> set2={3,4,5}
which it is called. For this, we have the >>> set1.intersection_update(set2)
intersection_update() intersection_update() method. >>> set1
{3}
>>> set1={1,2,3}
>>> set2={3,4,5}
this method updates >>> set1.difference_update(set2)
difference_update() the Python set with the difference. >>> set1
{1,2}
>>> set1={1,2,3}
it updates the set on which it is called >>> set2={3,4,5}
>>> set1.symmetric_difference_update(set2)
symmetric_difference_updatwith the symmetric difference. >>> set1
e() {1, 2, 4, 5}
creates a shallow copy of the >>> set4=set1.copy()
>>> set1,set4
copy() Python set. ({1, 2, 4, 5}, {1, 2, 4, 5})

>>> {1,3,2}.isdisjoint({4,5,6})
returns True if two sets have a null
isdisjoint() True
intersection.
returns true if the set in the argument >>> {1,2}.issubset({1,2,3})
issubset() contains this set. True
Like the issubset() method, this one returns >>> {1,3,4}.issuperset({1,2})
issuperset() True if the set contains the set in the
False
argument.
Python - Dictionary
• A dictionary is mutable and is another container type that can store
any number of Python objects, including other container types.
• Dictionaries consist of pairs (called items) of keys and their
corresponding values.
• Python dictionaries are also known as associative arrays or hash tables.
• The general syntax of a dictionary is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
• You can create dictionary in the following way as well:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
• Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces.
An empty dictionary without any items is written with just two curly
braces, like this: {}.
dict() Function :

• Python provides built-in function dict() for creating


a dictionary.
>>> d1=dict({1: "Orange", 2: "Mango", 3: "Banana"})
>>> d2=dict([(1, "Red"),(2, "Green"),(3, "Yellow")])
>>> d3=dict(one=1, two=2, three=3)
>>> d2
{1: 'Red',2: 'Green',3: 'Yellow'}
>>> d3
{'one':1, 'two':2, 'three':3}
Creating Dictionary Cont…

• Create Dictionary by assigning values to the keys entered by a user:


• We can insert a single element in the dictionary at run.
• The following program demonstrates the input procedure in the
dictionary:
n=int(input("Enter the number of elements:"))
d={}
print("Enter elements:")
for i in range(n):
k=input("Enter key:")
d[k]=input("Enter value:")
print(d)
Enter the number of elements:2
Enter elements:
Enter key: 1
Enter value: Orange
Enter key: 2
Enter value: Mango Enter {'1':'Orange','2':'Mango'}
Create Dictionary using split() method :

n=int(input("Enter the number of elements:"))


d=dict(input("Enter elements:").split() for i in range(n))
print("The created dictionary is:", d)

Enter the number of elements:3


Enter elements:a 12
Enter elements:b 13
Enter elements:c 14
The created dictionary is: {'a': '12', 'b': '13', 'c': '14'}
Accessing Values in Dictionary:
• To access dictionary elements, you use the familiar square
brackets along with the key to obtain its value:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
• This will produce following result:
dict['Name']: Zara
dict['Age']: 7
Accessing Values in Dictionary:
• If we attempt to access a data item with a key which is not
part of the dictionary, we get an error as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print ("dict['Alice']: ", dict['Alice'])

• This will produce following result:


dict['Zara']:
Traceback (most recent call last): File "test.py", line 4, in
<module> print "dict['Alice']: ", dict['Alice']; KeyError:
'Alice'
Accessing Values in Dictionary:

• Using the get() method and passing the key as a


parameter inside this method.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
>>>dict.get(‘Age') 7
>>> dict.get('Name') ‘Zara'

• Iterating Over the Dictionary : 1


8
cubes = {1:1, 2:8, 3:21, 4:64, 5:125} 21
64
for i in cubes: 125

print(cubes[i])
• To print all the items (key-value) in the dictionary : (1, 1)
(2, 8)
for i in cubes.items(): (3, 21)
print(i) (4, 64)
(5, 125)
Updating Dictionary:
• You can update a dictionary by adding a new entry or item (i.e., a
key-value pair), modifying an existing entry, or deleting an existing
entry as shown below:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age']);
print ("dict['School']: ", dict['School']);

This will produce following result:


dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements:
• You can either remove individual dictionary elements or clear the
entire contents of a dictionary. You can also delete entire dictionary
in a single operation.
• To explicitly remove an entire dictionary, just use the del statement:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

• This will produce following result. Note an exception raised, this is


because after del dict dictionary does not exist any more:
dict['Age']:
Traceback (most recent call last): File "test.py", line 8, in
<module> print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Deleting Values in Dictionary :
 The pop() Python Function is used to remove a particular element from a
dictionary by providing the key of the element :
cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
print(cubes.pop(4))
64
print(cubes) {1: 1, 2: 8, 3: 21, 5: 125}

• Delete Elements Using the popitem() Method:


 The popitem() method is used to remove any randomly picked element.

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


print(cubes.popitem())
(5, 125)
print(cubes) {1: 1, 2: 8, 3: 21, 4: 64}
Properties of Dictionary Keys:
• Dictionary values have no restrictions. They can be any arbitrary Python
object, either standard objects or user-defined objects. However, same
is not true for the keys.
• There are two important points to remember about dictionary keys:
• (a) More than one entry per key not allowed. Which means no duplicate
key is allowed. When duplicate keys encountered during assignment,
the last assignment wins.
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print ("dict['Name']: ", dict['Name']);

This will produce following result:


dict['Name']: Manni
• (b) Keys must be immutable. Which means you can use
strings, numbers, or tuples as dictionary keys but something
like ['key'] is not allowed.
• Example:
dict = {['Name']: 'Zara', 'Age': 7};
print ("dict['Name']: ", dict['Name']);

This will produce following result. Note an exception raised:


Traceback (most recent call last):
File "test.py", line 3, in <module> dict = {['Name']: 'Zara',
'Age': 7};
TypeError: list objects are unhashable
Built-in Dictionary Functions & Methods:

SN Function with Description


1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary
then it would return a dictionary type.
5 sorted()
Returns a sorted sequence of the keys in the dictionary. The sorting is
in ascending order, and doesn’t modify the original Python dictionary.
SN Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
2 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
3 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
4 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
5 dict.items()
Returns a list of dict's (key, value) tuple pairs
6 dict.keys()
Returns list of dictionary dict's keys
7 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
8 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
9 dict.values()
Returns list of dictionary dict2's values
Nested dictionary

• When we define a dictionary inside a dictionary is known as Nested


dictionary (a dictionary inside a dictionary)

nest_dic = {"dict_1":{"hello":"world", "python":"programming"},

"dict_2": {"tech":"geekbuzz", "OS":"window" } }


• Create a Nested Dictionary:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS', "price":67000} ,
2: {'Company' :'Samsung', 'model':'Note 10', "OS":'Android','price':87000}
}
>>>print(mobiles [1] ['model']) iphone
>>>print(mobiles [2] ['model']) Samsung
Strings in Python
• A string object is one of the sequence data types in Python. It
is an immutable sequence of Unicode characters.
• Strings are objects of Python's built-in class 'str'.
• String literals are written by enclosing a sequence of
characters in single quotes , double quotes , or triple quotes.

• >>> str1='hello'
>>> str2="hello"
>>> str3='''hello'''
>>> str4="""hello"""

• The triple quoted string is useful when a multi-line text is to


be >>>
defined as a string literal.
myString="""Welcome to
Sanjivani KBP
Polytechnic"""
Escape Sequences :
• The escape character is used to invoke an alternative
implementation of the subsequent character in a sequence.
• In Python backslash \ is used as an escape character.
• Here is a list of escape sequences.
Escape
Description Example Result
sequence
\a Bell or alert "\a" Bell sound
\b Backspace "ab\bc" ac
\f Formfeed "hello\fworld" hello world
\n Newline "hello\nworld" Hello
Octal notation, where n is in the
\nnn '\101' A
range 0-7
\t Tab 'Hello\tPython' Hello Python
Hexadecimal notation, where n is in
\xnn '\x41' A
the range 0-9, a-f, or A-F
Basic String Operations
Operator Description Example
>>> a='hello'
>>> b='world'
+ Appends the second string to the first >>> a+b
'helloworld'
>>> a='hello'
* Concatenates multiple copies of the same string >>> a*3
'hellohellohello'
>>> a = 'Python Program'
[] Returns the character at the given index >>> a[7]
P
>>> a = 'Python Program'
Fetches the characters in the range specified by
[:] two index operands separated by the : symbol
>>> a[7:15]
'Program'

>>> a = 'Python Program'


>>> 'X' in a
in Returns true if a character exists in the given string False
>>> 'Python' in a
True
>>> a = 'Python Program'
>>> 'X' not in a
Returns true if a character does not exist in the
not in given string
True
>>> 'Python' not in a
False
String Formatting :
• Interpolation of objects of different types at placeholders inside a string is
called string formatting.
• The % operator is used to perform string formatting.
• Format specification symbols (%d, %c, %f, %s, etc) used in C language are
utilized as placeholders in a string.
• Example,
>>> name="Bond"
>>> "My name is %s." % name 'My name is Bond.'

• You can have multiple parameters too.


>>> name="Bond"
>>> age=20
>>> "My name is %s and age is %d years." % (name, age)

'My name is Bond and age is 20 years.'


All C style format specification symbols are permitted

Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer


%u unsigned decimal integer
%o octal integer

%x / %X hexadecimal integer (lowercase letters)

%e / %E exponential notation (with lowercase 'e')

%f floating point real number


• You can specify the width of integer and float objects.
>>> a=1
>>> b=11
>>> c=111
>>> "a=%3d b=%3d c=%3d" % (a, b, c)
'a= 1 b= 11 c=111‘ #Additional spaces will be padded to the left.

 The following specifies the width of the float variable.

>>> percent=55.50
>>> "%5.2f" % percent '55.50'
>>> "%6.2f" % percent
' 55.50’
• The width of a string can also be specified. The default alignment is right. For
left alignment, give a negative sign to width.

>>>'%4s' % 'abc'
' abc'
>>>'%6s' % 'abc' ' abc'
format() method :
• The format() method can handle complex string formatting more efficiently.
• This method of in-built string class provides the ability to do complex variable
substitutions and value formatting.
• The general syntax of the format() method is as follows:
string.format(str1, str2,...)
• The string itself contains placeholders {}, in which the values of variables are
successively inserted.
• >>>name="Bill"
• >>>age=25
• >>>"My name is {} and I am {} years old.".format(name, age)

'My name is Bill and I am 25 years old.'

• You can also specify formatting symbols by using : instead of %. For example,
instead of %s use {:s} and instead of %d use {:d}.
• >>> "My name is {:s} and I am {:d} years old.".format(name, age)
'My name is Bill and I am 25 years old.'
• String alignment is done with <, > and ^ symbols in the place
holder causing left, right and center alignment, respectively.
• Default is left alignment.

>>> '{:>10}'.format('test') 'test '

>>> '{:<10}'.format('test') ' test'


>>> '{:^10}'.format('test')
' test '
String Methods
Method Description
capitalize() Converts the first character to upper case
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
lower() Converts a string into lower case
replace() Returns a string where a specified value is replaced with a specified value
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
upper() Converts a string into upper case
13. Python - Date and Time
• What is Tick?
• Time intervals are floating-point numbers in units of seconds.
Particular instants in time are expressed in seconds since 12:00am,
January 1, 1970(epoch).
• Example:
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1,
1970:", ticks
• This would produce a result something as follows:
Number of ticks since 12:00am, January 1, 1970:
7186862.73399
• Date arithmetic is easy to do with ticks. However, dates before the
epoch cannot be represented in this form. Dates in the far future also
cannot be represented this way - the cutoff point is sometime in
2038 for UNIX and Windows.
What is TimeTuple?
• Many of Python's time functions handle time as a tuple of 9
numbers, as shown below:
Inde
Field Values
x
0 4-digit year 2008

1 Month 1 to 12

2 Day 1 to 31

3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 61 (60 or 61 are leap-seconds)

6 Day of Week 0 to 6 (0 is Monday)

7 Day of year 1 to 366 (Julian day)

8 Daylight savings -1, 0, 1, -1 means library determines DST


The above tuple is equivalent to struct_time structure. This
structure has following attributes:
Index Attributes Values
0 tm_year 2008

1 tm_mon 1 to 12

2 tm_mday 1 to 31

3 tm_hour 0 to 23

4 tm_min 0 to 59

5 tm_sec 0 to 61 (60 or 61 are leap-seconds)

6 tm_wday 0 to 6 (0 is Monday)

7 tm_yday 1 to 366 (Julian day)

8 tm_isdst -1, 0, 1, -1 means library determines DST


Example I: Getting current time -:
• To translate a time instant from a seconds since the epoch
floating-point value into a time-tuple, pass the floating-
point value to a function (e.g., localtime) that returns a time-
tuple with all nine items valid:
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
• This would produce following result which could be
formatted in any other presentable form:
Local current time :
time.struct_time(tm_year=2011, tm_mon=10, tm_mday=8,
tm_hour=16, tm_min=17, tm_sec=51, tm_wday=5,
tm_yday=281, tm_isdst=1)
• Example II: Getting formatted time -:
• You can format any time as per your requirement, but simple
method to get time in readable format is asctime():
import time;
localtime =
time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime
• This would produce following result:
Local current time : Sat Oct 08 16:22:08 2011
Example III: Getting calendar for a month -:
• The calendar module gives a wide range of methods to play
with yearly and monthly calendars. Here we print a calendar
for a given month ( Jan 2008 ):
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;
• This would produce following result:
Here is the calendar:
October 2011
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
The time Module:
SN Function with Description
1 time.altzone
The offset of the local DST timezone, in seconds west of UTC, if one is
defined. This is negative if the local DST timezone is east of UTC (as in
Western Europe, including the UK). Only use this if daylight is nonzero.
2 time.asctime([tupletime])
Accepts a time-tuple and returns a readable 24-character string such as
'Tue Dec 11 18:07:14 2008'.
3 time.clock( )
Returns the current CPU time as a floating-point number of seconds. To
measure computational costs of different approaches, the value of
time.clock is more useful than that of time.time().
4 time.ctime([secs])
Like asctime(localtime(secs)) and without arguments is like asctime( )
5 time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a
time-tuple t with the UTC time. Note : t.tm_isdst is always 0
6 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a
time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on
whether DST applies to instant secs by local rules).
7 time.mktime(tupletime)
Accepts an instant expressed as a time-tuple in local time and returns a
floating-point value with the instant expressed in seconds since the epoch.
8 time.sleep(secs)
Suspends the calling thread for secs seconds.
9 time.strftime(fmt[,tupletime])
Accepts an instant expressed as a time-tuple in local time and returns a
string representing the instant as specified by string fmt.
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
Parses str according to format string fmt and returns the instant in time-
tuple format.
11 time.time( )
Returns the current time instant, a floating-point number of seconds since
the epoch.
12 time.tzset()
Resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.
There are following two important attributes available with time
module:

SN Attribute with Description


1 time.timezone
Attribute time.timezone is the offset in seconds of the local
time zone (without DST) from UTC (>0 in the Americas; <=0
in most of Europe, Asia, Africa).
2 time.tzname
Attribute time.tzname is a pair of locale-dependent strings,
which are the names of the local time zone without and with
DST, respectively.
The calendar Module
• The calendar module supplies calendar-related functions, including
functions to print a text calendar for a given month or year.
• By default, calendar takes Monday as the first day of the week and
Sunday as the last one. To change this, call
calendar.setfirstweekday() function.
• Here is a list of functions available with the calendar module:
SN Function with Description
1 calendar.calendar(year,w=2,l=1,c=6)

Returns a multiline string with a calendar for year year formatted into
three columns separated by c spaces. w is the width in characters of
each date; each line has length 21*w+18+2*c. l is the number of
lines for each week.
2 calendar.firstweekday( )

Returns the current setting for the weekday that starts each week. By
default, when calendar is first imported, this is 0, meaning Monday.
3 calendar.isleap(year)

Returns True if year is a leap year; otherwise, False.


4 calendar.leapdays(y1,y2)
Returns the total number of leap days in the years within range(y1,y2).
5 calendar.month(year,month,w=2,l=1)
Returns a multiline string with a calendar for month month of year year, one line
per week plus two header lines. w is the width in characters of each date; each line
has length 7*w+6. l is the number of lines for each week.
6 calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside month
month of year year are set to 0; days within the month are set to their day-of-
month, 1 and up.
7 calendar.monthrange(year,month)
Returns two integers. The first one is the code of the weekday for the first day of
the month month in year year; the second one is the number of days in the month.
Weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
Like print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
Like print calendar.month(year,month,w,l).
10 calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday codes are 0
(Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time instant in time-tuple form and returns
the same instant as a floating-point number of seconds since the epoch.
12 calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0 (Monday) to 6
(Sunday); month numbers are 1 (January) to 12 (December).

You might also like