0% found this document useful (0 votes)
14 views50 pages

Unit 4

The document provides an overview of numbers and mathematical methods in Python, detailing various number data types including integers, floats, and complex numbers. It also covers number type conversion, built-in mathematical functions, and random number generation functions. Key functions such as abs, ceil, log, and random are highlighted with examples for practical understanding.

Uploaded by

tinsades
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)
14 views50 pages

Unit 4

The document provides an overview of numbers and mathematical methods in Python, detailing various number data types including integers, floats, and complex numbers. It also covers number type conversion, built-in mathematical functions, and random number generation functions. Key functions such as abs, ceil, log, and random are highlighted with examples for practical understanding.

Uploaded by

tinsades
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/ 50

Python for Data Science (PDS) (3150713)

Unit-4
numbers and mathematical methods in
Python
 Outline
Looping

✓ Numbers in Python
✓ Random number functions
✓ Trigonometric functions
✓ Mathematical constants
✓ Dates and times
Numbers in Python
 Number data types store numeric values. They are immutable data types.
 This means, changing the value of a number data type results in a newly allocated object.
 Number objects are created when you assign a value to them

e.g. a=200 200


Print(a) #200
a
a= 300
Print(a) #300 300

 You can also delete the reference to a number object by using the del
statement.

i.e. del a or if you have many variables use like del a,b,c

Numbers in Python
 Python supports different numerical types:
 int (signed integers): are often called just integers or ints (- or + whole numbers with no decimal point).
 Integers in Python 3 are of unlimited size.
 E.g. x=12345678901234567890123456789012345678901234567890123456789012345678901
 Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore.
 float (floating point real values) : Also called floats, they represent real numbers and are
written with a decimal point dividing the integer and the fractional parts.
 Floats may also be in scientific notation, with E or e indicating the power of 10
 E.g. 3.8e2 = 3.8 x 102 = 380).
 complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number).
 The real part of the number is a, and the imaginary part is b.
 Complex numbers are not used much in Python programming.
 E.g. x=3.25j or y=2.35j
Numbers in Python
 An integer can be represented in hexa-decimal or octal form or binary.
 NB: in order to represent an integer in hexa decimal, start with 0x or 0X always.
 in order to represent an integer in octal/ base eight, start with 0o or 0O always.
 in order to represent an integer in binary, start with 0b or 0B always.
 E.g. num0=0xA0F #represents integer 2575
num1=0XED #represents integer 237
num2=0o34 #represents integer 28
num3 =0O654 #represents integer 428
num4 = 0b1010 #represents integer 10
num5 = 0B1001 #represents integer 9
num6 =0b1010110 #represents integer 86
num=0OADG #impossible
num=0O238 #impossible
num=0b1021 #impossible
Numbers in Python
 Number Type Conversion
 Python converts numbers internally in an expression containing mixed types to a common type
for evaluation.
 Type int(x) to convert x to a plain integer. E.g. int(2.3) #converts to 2
 Type long(x) to convert x to a long integer but it can not work in python 3 since no 'long integer'
in Python 3
 Type float(x) to convert x to a floating-point number.
 E.g. float(2) #converts to 2.0
 Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
 E.g. complex(2) #converts to (2+0j) or complex(2.22) #converts to (2.22+0j)
 Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part
y. x and y are numeric expressions.
 E.g. complex(2,3) #converts to (2+3j) or complex(2.22,5) #converts to (2.22+5j) or
complex(5,2.22) #converts to (5+2.22j)
Mathematical functions in Python
 Python supports the following built-in functions that perform mathematical calculations.
Functions Descriptions
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x.
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3; Instead use return (x>y)-(x<y).
exp(x) The exponential of x: ex
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x.
log(x) The natural logarithm of x, for x> 0.
log10(x) The base-10 logarithm of x for x> 0.
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity.
Mathematical functions in Python
 Con…
Functions Descriptions
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity.
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as
x. The integer part is returned as a float.
pow(x, y) pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from zero as a tie-
breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
x - This is a numeric expression.
n - Represents number of digits from decimal point up to which x is to be rounded. Default is 0.
sqrt(x) sqrt(x) The square root of x for x > 0.

 NB: in order to use most of those built in functions, you first import the mathematical library
 i.e. import math
Mathematical functions in Python
 Examples:
Output:
 abs(x) abs(-30) : 30
print ("abs(-30) : ", abs( -30)) abs(15.2) : 15.2
print ("abs(15.2) : ", abs(15.2))
 math.ceil(x)
import math
print ("math.ceil(-45.17) : ", math. ceil(- 45.17)) Output:
print ("math.ceil(100.12) : ", math. ceil(100.12)) math. ceil( -45.17) : -45
math. ceil( 100.12) : 101
print ("math.ceil(100.72) : ", math. ceil(100.72))
math. ceil( 100.72) : 101
print ("math.ceil(math.pi) : " , math. ceil( math. pi)) math. ceil( math. pi) : 4
 math.exp( x )
import math Output:
print ("math.exp(-45.17) : ", math.exp( -45.17)) math.exp(-45.17) : 2.4150062132629406e-20
print ("math.exp(100.12) : ", math.exp(100.12)) math.exp(100.12) : 3.0308436140742566e+43
print ("math.exp(100.72) : ", math.exp(100.72)) math.exp(100.72) : 5.522557130248187e+43
print ("math.exp(math.pi) : ", math.exp(math.pi)) math.exp(math.pi) : 23.140692632779267
Mathematical functions in Python con…
 math.fabs(x)
import math
print ("math.fabs( -45.17) : " , math. fabs(-45.17)) Output:
print ("math.fabs(100.12) : " , math. fabs(100.12)) math. fabs(-45.17) : 45.17
print ("math.fabs(100.72) : " , math. fabs(100.72)) math. fabs(100) : 100.0
print ("math.fabs(math.pi) : ", math. fabs(math. pi)) math. fabs(100.72) : 100.72
math. fabs(math. pi) :
3.141592653589793
 math. floor(x)
import math
print ("math.floor(-45.17) : ", math. floor(-45.17))
print ("math.floor(100.12) : " , math. floor(100.12)) Output:
math. floor(-45.17) : -46
print ("math.floor(100.72) : " , math. floor(100.72)) math. floor(100.12) : 100
print ("math.floor(math.pi) : " , math. floor(math. pi)) math. floor(100.72) : 100
math. floor(math. pi) : 3
Mathematical functions in Python con…
 math.log(x)
import math
print ("math.log(100.12) : ", math. log(100.12)) Output:
math. log(100.12) : 4.6063694665635735
print ("math.log(100.72) : ", math. log(100.72))
math. log(100.72) : 4.612344389736092
print ("math.log(math.pi) : ", math. log(math. pi)) math. log(math. pi) : 1.1447298858494002
 math. log10(x)
import math
print ("math.log10(100.12) : ", math.log10(100.12)) Output:
print ("math.log10(100.72) : ", math.log10(100.72)) math.log10(100.12) : 2.0005208409361854
math.log10(100.72) : 2.003115717099806
print ("math.log10(119) : ", math.log10(119)) math.log10(119) : 2.0755469613925306
print ("math.log10(math.pi) : ", math.log10(math.pi)) math.log10(math.pi) : 0.49714987269413385
 max( x, y, z,… )
print ("max(80, 100, 1000) : ", max(80, 100, 1000)) Output:
print ("max(-20, 100, 400) : ", max( -20, 100, 400)) max(80, 100, 1000) : 1000
print ("max(-80, -20, -10) : ", max( -80, -20, -10)) max(-20, 100, 400) : 400
max(-80, -20, -10) : -10
Mathematical functions in Python con…
 min(x, y, z, …)
print ("min(80, 100, 1000) : ", min(80, 100, 1000)) Output:
min(80, 100, 1000) : 80
print ("min(-20, 100, 400) : ", min( -20, 100, 400))
min(-20, 100, 400) : -20
print ("min(-80, -20, -10) : ", min( -80, -20, -10)) min(-80, -20, -10) : -80
print ("min(0, 100, -400) : ", min(0, 100, -400)) min(0, 100, -400) : -400
 math. modf(x): returns the fractional and integer parts of x in a two-item tuple.
import math
print ("math.modf(100.12) : ", math.modf(100.12)) Output:
math.modf(100.12) : (0.12000000000000455, 100.0)
print ("math.modf(100.72) : ", math.modf(100.72))
math.modf(100.72) : (0.7199999999999989, 100.0)
print ("math.modf(119) : ", math.modf(119)) math.modf(119) : (0.0, 119.0)
print ("math.modf(math.pi) : ", math.modf(math.pi)) math.modf(math.pi) : (0.14159265358979312, 3.0)

 math.pow( x, y )
Output:
print ("math.pow(100, 2) : ", math.pow(100, 2)) math.pow(100, 2) : 10000.0
print ("math.pow(100, -2) : ", math.pow(100, -2)) math.pow(100, -2) : 0.0001
print ("math.pow(2, 4) : ", math.pow(2, 4)) math.pow(2, 4) : 16.0
print ("math.pow(3, 0) : ", math.pow(3, 0)) math.pow(3, 0) : 1.0
Mathematical functions in Python con…
 round(x [, n]): returns x rounded to n digits from the decimal point.

print ("round(70.23456) : ", round(70.23456)) Output:


round(70.23456) : 70
print ("round(56.659,1) : ", round(56.659,1)) round(56.659,1) : 56.7
print ("round(80.264, 2) : ", round(80.264, 2)) round(80.264, 2) : 80.26
print ("round(100.000056, 3) : ", round(100.000056, 3)) round(100.000056, 3) : 100.0
print ("round(-100.000056, 3) : ", round( -100.000056, 3)) round(-100.000056, 3) : -100.0

 math. sqrt(x)
import math Output:
math.sqrt(100) : 10.0
print ("math.sqrt(100) : ", math.sqrt(100)) math.sqrt(7) : 2.6457513110645907
print ("math.sqrt(7) : ", math.sqrt(7)) math.sqrt(math.pi) : 1.7724538509055159

print ("math.sqrt(math.pi) : ", math.sqrt(math.pi))


Random number functions in Python
 Random numbers are used for games, simulations, testing, security, and privacy applications.
 Python includes the following functions that are commonly used.
Functions Descriptions
choice(seq) A random item from a list, tuple, or string.
randrange ([start,] stop [,step]) A randomly selected element from range(start, stop, step).
start - Start point of the range. This would be included in the range. Default is 0.
stop - Stop point of the range. This would be excluded from the range.
step - Value with which number is incremented. Default is 1.
random() A random float r, such that 0 is less than or equal to r and r is less than 1.
seed([x]) Sets the integer starting value used in generating random numbers. Call
this function before calling any other random module function. Returns
None.
shuffle(lst) Randomizes the items of a list in place. Returns None.
uniform(x, y) A random float r, such that x is less than or equal to r and r is less than y.
Random number functions in Python
 Examples: choice(seq) : returns a random item from a list, tuple, or string.
Import random
print (“Generates number from range(100) : ", random.choice(range(100)))
print (“Generates element from list : ", random.choice([1,2, 3, 5, 9]))
print (" Returns character from 'Hello World' : ", random.choice('Hello World’))
Output:
Generates number from range(100) : 19
Generates element from list : 9
Returns character from 'Hello World': r
 randrange(x) : returns a randomly selected element from range(start, stop, step).
import random
# randomly select an odd number between 1-100 Output:
print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2)) randrange(1,100, 2) : 83
randrange(100) : 93
# randomly select a number between 0-99
print ("randrange(100) : ", random.randrange(100))
Random number functions in Python conn…
 random() : returns a random floating point number in the range [0.0, 1.0].
Import random
Output:
print ("random() : ", random.random()) # 1st random number random() : 0.281954791393
print ("random() : ", random.random()) # 2nd random number random() : 0.309090465205
 seed ([x], [y]): is used to initialize the random number generator and returns None.
x - is the seed for the next random number. If omitted/lost, then it takes system time to generate the next
random number. If x is an int, it is used directly. Default value is None, and if None, the generator uses the
current system time.
Y - is version number (default value is 2).
it is an integer specifying how to convert the x parameter into an integer.
Eg. Output:
print(random.seed(1,10)) None
print(random.seed(1)) None
print(random.seed()) None
 str, byte or byte array object gets converted in int.
 eg. random.seed("hello",2), print(random.random()) #output: 0.3537754404730722
Random number functions in Python conn…
 seed ([x], [y]): con…
Use the seed() method to customize the start number of the random number generator.
Note: If you use the same seed value twice you will get the same random number twice.
e.g.
For more elaboration see those examples:
import random
With seed Without seed
>>> random.seed(10) for i in range(3): for i in range(3):
>>> random.random() # generates: 0.5714025946899135 random.seed(10) #random.seed(10)
print(random.random()) print(random.random())
>>> random.seed(10) Output: Output:
>>> random.random() # generates: 0.5714025946899135 0.5714025946899135 0.4288890546751146
0.5714025946899135 0.5780913011344704
>>> random.seed(10) 0.5714025946899135 0.20609823213950174
>>> random.random() # generates: 0.5714025946899135
# but without seed() it generates different numbers
>>> random.random() #0.8444218515250481
>>> random.random() #0.7579544029403025
Random number functions in Python conn…
 shuffle(lst, [random]) : returns reshuffled list randomly.
 lst - This could be a list or tuple.
 random - This is an optional 0 argument function returning float between 0.0 -1.0. Default is None.

Import random
list = [20, 16, 10, 5]; Output:
random.shuffle(list) Reshuffled list : [16, 5, 10, 20]
print ("Reshuffled list : ", list) reshuffled list : [20, 5, 10, 16]
random.shuffle(list)
print ("Reshuffled list : ", list)
 uniform (x, y): returns a random float r, such that x is less than or equal to r and r is less than y.
 x - Sets the lower limit of the random float.
 y - Sets the upper limit of the random float. But if y<x, the lower limit is not work.
import random Output:
Random Float uniform(5, 10) :
print ("Random Float uniform(5, 10) : ", random.uniform(5, 10)) 5.52615217015
Random Float uniform(7, 14) :
print ("Random Float uniform(7, 14) : ", random.uniform(7, 14)) 12.5326369199
Trigonometric functions in Python
 Trigonometry functions such as sine, cosine, and tangent can also be calculated using the Python
REPL (Read Evaluate Print Loop) which is used to perform calculations at the Python Prompt.
 Python includes the following functions that perform trigonometric calculations.
Functions Descriptions
acos(x) Return the arc cosine of x, in radians
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y)
sin(x) Return the sine of x radians
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.

Trigonometric functions in Python conn…
 Examples: acos(x)
 x - This must be a numeric value in range -1 to 1. If x is greater than 1 then it will generate 'math domain
error'.

Import math
print ("acos(0.64) : ", math.acos(0.64))
Output:
print ("acos(0) : ", math.acos(0))
acos(0.64) : 0.876298061168
print ("acos(-1) : ", math.acos(-1)) acos(0) : 1.57079632679
print ("acos(1) : ", math.acos(1)) acos(-1) : 3.14159265359
acos(1) : 0.0
 asin(x)
 x – must be a numeric value in range -1 to 1. If x is greater than 1 then it will generate 'math domain error'.
import math
print ("asin(0.64) : ", math.asin(0.64)) Output:
print ("asin(0) : ", math.asin(0)) asin(0.64) : 0.694498265627
print ("asin(-1) : ", math.asin(-1)) asin(0) : 0.0
asin(-1) : -1.57079632679
print ("asin(1) : ", math.asin(1)) asin(1) : 1.5707963267
Trigonometric functions in Python conn…
 atan(x)
 x - must be a numeric value
Import math
print ("atan(0.64) : ", math.atan(0.64)) Output:
print ("atan(0) : ", math.atan(0)) atan(0.64) : 0.569313191101
atan(0) : 0.0
print ("atan(10) : ", math.atan(10)) atan(10) : 1.4711276743
print ("atan(-1) : ", math.atan(-1)) atan(-1) : -0.785398163397
print ("atan(1) : ", math.atan(1)) atan(1) : 0.785398163397

 atan2(x, y) : returns atan(y / x), in radians


 X and y - must be a numeric value
import math
Output:
print ("atan2(-0.50,-0.50) : ", math.atan2(-0.50,-0.50)) atan2(-0.50,-0.50) : -2.35619449019
print ("atan2(0.50,0.50) : ", math.atan2(0.50,0.50)) atan2(0.50,0.50) : 0.785398163397
print ("atan2(5,5) : ", math.atan2(5,5)) atan2(5,5) : 0.785398163397
print ("atan2(-10,10) : ", math.atan2(-10,10)) atan2(-10,10) : -0.785398163397
print ("atan2(10,20) : ", math.atan2(10,20)) atan2(10,20) : 0.463647609001
Trigonometric functions in Python conn…
 cos(x) : x - must be a numeric value .
 returns a numeric value between -1 and 1, which represents the cosine of the angle.
Import math
print ("cos(3) : ", math.cos(3)) Output:
print ("cos(-3) : ", math.cos(-3)) cos(3) : -0.9899924966
print ("cos(0) : ", math.cos(0)) cos(-3) : -0.9899924966
cos(0) : 1.0
print ("cos(math.pi) : ", math.cos(math.pi)) cos(math.pi) : -1.0
print ("cos(2*math.pi) : ", math.cos(2*math.pi)) cos(2*math.pi) : 1.0
 hypot (x, y) : returns Euclidean norm, sqrt(x*x + y*y).
 X and y - must be a numeric value
import math
Output:
print ("hypot(3, 2) : ", math.hypot(3, 2)) hypot(3, 2) : 3.60555127546
print ("hypot(-3, 3) : ", math.hypot(-3, 3)) hypot(-3, 3) : 4.24264068712
print ("hypot(0, 2) : ", math.hypot(0, 2)) hypot(0, 2) : 2.0
Trigonometric functions in Python conn…
 sin(x) : x - must be a numeric value .
 returns a numeric value between -1 and 1, which represents the sine of the parameter x.
Import math
Output:
print ("sin(3) : ", math.sin(3)) sin(3) : 0.14112000806
print ("sin(-3) : ", math.sin(-3)) sin(-3) : -0.14112000806
print ("sin(0) : ", math.sin(0)) sin(0) : 0.0
print ("sin(math.pi) : ", math.sin(math.pi)) sin(math.pi) : 1.22460635382e-16
sin(math.pi/2) : 1
print ("sin(math.pi/2) : ", math.sin(math.pi/2))
 tan (x) : X - must be a numeric value
 returns a numeric value between -1 and 1, which represents the tangent of the parameter x.
import math
Output:
print ("(tan(3) : ", math.tan(3))
(tan(3) : -0.1425465430742778
print ("tan(-3) : ", math.tan(-3)) tan(-3) : 0.1425465430742778
print ("tan(0) : ", math.tan(0)) tan(0) : 0.0
print ("tan(math.pi) : ", math.tan(math.pi)) tan(math.pi) : -1.2246467991473532e-16
print ("tan(math.pi/2) : ", math.tan(math.pi/2)) tan(math.pi/2) : 1.633123935319537e+16
Trigonometric functions in Python conn…
 degrees (x) : returns the degree value of an angle and x must be a numeric value .
Import math
print ("degrees(3) : ", math.degrees(3)) Output:
degrees(3) : 171.88733853924697
print ("degrees(-3) : ", math.degrees(-3))
degrees(-3) : -171.88733853924697
print ("degrees(0) : ", math.degrees(0)) degrees(0) : 0.0
print ("degrees(math.pi) : ", math.degrees(math.pi)) degrees(math.pi) : 180.0
print ("degrees(math.pi/2) : ", math.degrees(math.pi/2)) degrees(math.pi/2) : 90.0
degrees(math.pi/4) : 45.0
print ("degrees(math.pi/4) : ", math.degrees(math.pi/4))
 radians (x) : returns radian value of an angle and x must be a numeric value .
import math
print ("radians(3) : ", math.radians(3)) Output:
print ("radians(-3) : ", math.radians(-3)) radians(3) : 0.0523598775598
radians(-3) : -0.0523598775598
print ("radians(0) : ", math.radians(0)) radians(0) : 0.0
print ("radians(math.pi) : ", math.radians(math.pi)) radians(math.pi) : 0.0548311355616
radians(math.pi/2) : 0.0274155677808
print ("radians(math.pi/2) : ", math.radians(math.pi/2))
Mathematical constants in Python
 There are two mathematical constants in python.

 The mathematical constant pi.

 The mathematical constant e.


Examples:
Import math
Output:
print(math.pi)
3.141592653589793
print(10*math.pi) 31.41592653589793
print(10-math.pi) 6.858407346410207
print(math.e) 2.718281828459045
52.71828182845905
print(math.e+50)
Dates and times in Python
 A Python program can handle date and time in several ways.
 Converting between date formats is a common chore for computers.
 There is a popular time module available in Python, which provides functions for working
with times, and for converting between representations.
 The function time.time() returns the current system time in ticks since 12:00am, January 1,
1970(epoch).
The epoch is the point where the time starts, the return value of time.gmtime(0).
 output: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=3, tm_yday=1, tm_isdst=0)
 It is, January 1, 1970, 00:00:00 (UTC) (i.e., Coordinated Universal Time) on all platforms.
 The term seconds since the epoch refers to the total number of elapsed seconds since the
epoch, typically excluding leap seconds.
 Leap seconds are excluded from this total on all platforms.
 The functions in this module may not handle dates and times before the epoch or far in the future.
i.e., the cutoff point is sometime in 2038 for UNIX and Windows.
Dates and times in Python
 Time Tuple: Many of the Python's time functions handle time as a tuple of 9 numbers:
Index Field Values
0 4-digit year 2016
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 current epoch is got by time.time()
import time;
print ("Number of ticks since 12:00am, January 1, 1970 is :", time. time())
Output: Number of ticks since 12:00am, January 1, 1970 is : 1709613215.2486975
Dates and times in Python
 Example-2:
Output:
Import time time.struct_time(tm_year=2024, tm_mon=3, tm_mday=5, tm_hour=7, tm_min=34,
print (time. localtime()) tm_sec=12, tm_wday=1, tm_yday=65, tm_isdst=0)

 Getting formatted time


Import time
print ("Local current time : “, time.asctime(time.localtime(time.time())))
Output:
Tue Mar 5 07:38:24 2024
 Getting calendar for a month Output:
import calendar
cal= calendar. month(2023, 3)
print("Here is the calendar: “)
print(cal)
Dates and times in Python
 Time Modules

Methods with their descriptions


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). Use this if
the daylight is nonzero.
time.asctime([tupletime]): Accepts a time-tuple and returns a readable 24-character string such as
'Tue Dec 11 18:07:14 2008'.
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().
time.ctime([secs]); Like asctime(localtime(secs)) and without arguments is like asctime( )
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
Dates and times in Python
 Time Modules con…
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).
time.mktime(tupletime): Accepts an instant expressed as a time-tuple in local time and returns a
floatingpoint value with the instant expressed in seconds since the epoch.
time.sleep(secs): Suspends the calling thread for secs seconds.
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.
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.
time.time( ): Returns the current time instant, a floating-point number of seconds since the epoch.
time.tzset(): Resets the time conversion rules used by the library routines.
The environment variable TZ specifies how this is done.
Dates and times in Python
 Time time.altzone : is the attribute of the time module.
 returns the offset of the local DST timezone, in seconds west of UTC, if one is defined.
 E.g. import time
print ("time.altzone : ", time.altzone) Output:
time.altzone : -14400

 Time asctime([t]) method: converts a tuple or struct_time representing a time as returned by


gmtime() or localtime() to a 24-character string.
 t - This is a tuple of 9 elements or struct_time representing a time as returned by gmtime()
or localtime() function.
 returns 24-character string.
 E.g.
import time
t = time.localtime() Output:
print ("asctime :",time.asctime(t)) asctime : Tue Mar 5 09:25:47 2024
Dates and times in Python
 Time clock() Method: returns the current processor time as a floating point number expressed in
seconds on Unix.
 On Windows, this function returns wall-clock seconds elapsed since the first call to this
function, as a floating point number, based on the Win32 function QueryPerformanceCounter.
 But clock() is removed in python >= 3.3. use time.perf_counter() or time.process_time()
 E.g. import time
def procedure():
time.sleep(2.5)
# measure process time
#t0 = time.clock()
t0=time.perf_counter()
procedure()
print (time.perf_counter() - t0, "seconds process time")
# measure wall time Output:
t0=time.perf_counter() 2.5059095 seconds process time
procedure() 2.5050843000000005 seconds wall time
print (time.perf_counter() - t0, "seconds wall time")
Dates and times in Python
 Time ctime([sec]) Method: converts a time expressed in seconds since the epoch to a string
representing local time.
 If secs is not provided or None, the current time as returned by time() is used.
 This function is equivalent to asctime(localtime(secs)).
 Locale information is not used by ctime().
 sec - These are the number of seconds to be converted into string representation and does not
return any value.

Eg.
import time
print ("ctime : ", time.ctime())
Output:
ctime : Wed Mar 6 09:58:21 2024
Dates and times in Python
 Time gmtime([sec]) Method: converts a time expressed in seconds since the epoch to a
struct_time in UTC in which the dst flag is always zero.
 If secs is not provided or None, the current time as returned by time() is used.
 sec - These are the number of seconds to be converted into structure struct_time
representation and does not return any value.

Eg.
import time
print ("gmtime :", time.gmtime(1455508609.34375))

Output:
gmtime : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=3,
tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0)
Dates and times in Python
 Time localtime([sec]) Method: similar to gmtime() but it converts number of seconds to local
time.
 If secs is not provided or None, the current time as returned by time() is used.
 The dst flag is set to 1 when DST applies to the given time.
 sec - These are the number of seconds to be converted into string representation and does not
return any value.
Eg.
import time
print ("time.localtime() : %s" , time.localtime())

Output:
time.localtime() : %s time.struct_time(tm_year=2024, tm_mon=3, tm_mday=6, tm_hour=10,
tm_min=15, tm_sec=56, tm_wday=2, tm_yday=66, tm_isdst=0)
Dates and times in Python
 Time mktime(t) Method: is the inverse function of localtime().
 Its argument is the struct_time or full 9-tuple and it returns a floating point number, for
compatibility with time().
 If the input value cannot be represented as a valid time, either OverflowError or ValueError
will be raised.
 t - This is the struct_time or full 9-tuple.
 It returns a floating point number, for compatibility with time().
 E.g. import time
t = (2024, 2, 15, 10, 13, 38, 1, 48, 0) # i.e, (tm_year=2024, tm_mon=3, tm_mday=6, tm_hour=10,
tm_min=15, tm_sec=56, tm_wday=2, tm_yday=66, tm_isdst=0)
d=time.mktime(t)
print ("time.mktime(t) : %f" % d)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(d)))
Output:
time.mktime(t) : 1707981218.000000
asctime(localtime(secs)): Thu Feb 15 10:13:38 2024
Dates and times in Python
 Time sleep(t) Method: suspends execution for the given number of seconds.
 The argument may be a floating point number to indicate a more precise sleep time.
 The actual suspension time may be less than that requested because any caught signal
will terminate the sleep() following execution of that signal's catching routine.
 t - This is the number of seconds for which the execution is to be suspended and does not
return any value.

Eg.
import time
print ("Start : %s" % time.ctime())
time.sleep(5)
Output:
print ("End : %s" % time.ctime())
Start : Wed Mar 6 10:25:30 2024
End : Wed Mar 6 10:25:50 2024
Dates and times in Python
 Time strftime(format [,t]) Method: converts a tuple or struct_time representing a time as returned
by gmtime() or localtime() to a string as specified by the format argument.
 If t is not provided, the current time as returned by localtime() is used. The format must be a string.
 An exception ValueError is raised if any field in t is outside of the allowed range.
 t - This is the time in number of seconds to be formatted.
 format - This is the directive which would be used to format given time.
 The following directives can be embedded in the format string
%a - abbreviated weekday name
%A - full weekday name
%b - abbreviated month name
%B - full month name
%c - preferred date and time representation
%C - century number (the year divided by 100, range 00 to 99)
%d - day of the month (01 to 31)
%D - same as %m/%d/%y
%e - day of the month (1 to 31)
Dates and times in Python
 Time strftime(format [,t]) Method: directives con…
%g - like %G, but without the century
%G - 4-digit year corresponding to the ISO week number (see %V).
%h - same as %b
%H - hour, using a 24-hour clock (00 to 23)
%I - hour, using a 12-hour clock (01 to 12)
%j - day of the year (001 to 366)
%m - month (01 to 12)
%M - minute
%n - newline character
%p - either am or pm according to the given time value
%r - time in a.m. and p.m. notation
%R - time in 24 hour notation
%S - second
%t - tab character
%T - current time, equal to %H:%M:%S
Dates and times in Python
 Time strftime(format [,t]) Method: directives con…
%u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
%U - week number of the current year, starting with the first Sunday as the first day of the
first week
%V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first
week that has at least 4 days in the current year, and with Monday as the first day of the week
%W - week number of current year, starting with the first Monday as first day of first week
%w - day of the week as a decimal, Sunday=0
%x - preferred date representation without the time
%X - preferred time representation without the date
%y - year without a century (range 00 to 99)
%Y - year including the century
%Z or %z - time zone or name or abbreviation
%% - a literal % character
Dates and times in Python
 Time strftime(format [,t]) Method: examples
Eg.
import time
t = (2024, 12, 31, 10, 39, 45, 1, 48, 0)
t = time.mktime(t)
print (time.strftime("%b %d %Y %H:%M:%S", time.localtime(t)))
print (time.strftime("%B %D %Y %H:%M:%S", time.localtime(t)))
print (time.strftime("%B %D %Y %H:%M:%S", time.localtime(955458)))
Output:
Dec 31 2024 10:39:45
December 12/31/24 2024 10:39:45
January 01/12/70 1970 04:24:18
Dates and times in Python
 Time strptime(string[, format]) Method: parses a string representing a time according to a format.
 The return value is a struct_time as returned by gmtime() or localtime().
 The format parameter uses the same directives as those used by strftime(); it defaults to
"%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().
 string - This is the time in string format which would be parsed based on the given format.
 format - This is the directive which would be used to parse the given string.
Eg.
import time
struct_time = time.strptime("30 12 2024", "%d %m %Y")
print ("tuple : ", struct_time)

Output:
tuple : time.struct_time(tm_year=2024, tm_mon=12, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=0, tm_yday=365, tm_isdst=-1)
Dates and times in Python
 Time time() Method: returns the time as a floating point number expressed in seconds since
the epoch, in UTC.

Eg.
import time
print ("time.time(): %f " % time.time())
print (time.localtime(time.time()))
print (time.asctime(time.localtime(time.time())))
Output:
time.time(): 1709791146.462177
time.struct_time(tm_year=2024, tm_mon=3, tm_mday=7, tm_hour=8, tm_min=59, tm_sec=32, tm_wday=3,
tm_yday=67, tm_isdst=0)
Thu Mar 7 09:00:04 2024
Dates and times in Python
 Time tzset() Method: resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.
 The standard format of the TZ environment variable is (whitespace added for clarity):-
 std offset [dst [offset [,start[/time], end[/time]]]]
 std and dst: Three or more alphanumerics giving the timezone abbreviations.
 These will be propagated into time.tzname.

 offset: The offset has the form: .hh[:mm[:ss]].


 This indicates the value added the local time to arrive at UTC.
 If preceded by a '-', the timezone is east of the Prime Meridian; otherwise, it is west.
 If no offset follows dst, summer time is assumed to be one hour ahead of standard time.
Dates and times in Python
 start[/time], end[/time]: Indicates when to change to and back from DST. The format of the
start and end dates are one of the following:
 Jn: The Julian day n (1 <= n <= 365). Leap days are not counted, so in all years
February 28 is day 59 and March 1 is day 60.
 n: The zero-based Julian day (0 <= n <= 365). Leap days are counted, and it is possible to
refer to February 29.
 Mm.n.d: The d'th day (0 <= d <= 6) or week n of month m of the year (1 <= n <= 5, 1 <=
m <= 12, where week 5 means 'the last d day in month m' which may occur in either the
fourth or the fifth week). Week 1 is the first week in which the d'th day occurs. Day zero
is Sunday.
 time: This has the same format as offset except that no leading sign ('-' or '+')
is allowed. The default, if time is not given, is 02:00: 00.
Dates and times in Python
 Time tzset() Method: example

import time
import os
# Define TZ environment variable
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0’
#time.tzset() # not available in Windows
print (time.strftime('%X %x %Z'))
os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0’
#time.tzset()
print (time.strftime('%X %x %Z'))
Output:
09:17:15 03/07/24 E. Africa Standard Time
09:17:45 03/07/24 E. Africa Standard Time
Dates and times in Python
 Time module attributes
 There are two important attributes available with time module.
 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).
 time.tzname: is a pair of locale-dependent strings, which are the names of the local time zone
without and with DST, respectively.
import time
time.timezone
Output:
time.tzname -10800
'E. Africa Standard Time', 'E. Africa Daylight Time')
Dates and times in Python
 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 the calendar.setfirstweekday() function.
Function with Description
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.
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.
calendar.isleap(year): Returns True if year is a leap year; otherwise, False.
calendar.leapdays(y1,y2): Returns the total number of leap days in the years within range(y1,y2).
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.
Dates and times in Python
 The calendar module: conn…
Function with Description
calendar.monthcalendar(year,month): Returns a list of lists of ints. Each sublist denotes a week. Days
outside month of year year are set to 0; days within the month are set to their day-ofmonth, 1 and up.
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.
calendar.prcal(year,w=2,l=1,c=6): Like print calendar.calendar(year,w,l,c).
calendar.prmonth(year,month,w=2,l=1): Like print calendar.month(year,month,w,l).
calendar.setfirstweekday(weekday): Sets the first day of each week to weekday code weekday. Weekday
codes are 0 (Monday) to 6 (Sunday).
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.
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).
Dates and times in Python
 Other Modules & Functions
 Use the list of other important modules and functions to play with date & time in
Python:
 The datetime Module
 The pytz Module
 The dateutil Module

You might also like