0% found this document useful (0 votes)
11 views

8_time, random, datetime

The document provides an introduction to the time, random, and datetime modules in Python, detailing their functionalities and key functions. It explains how the time module handles time-related tasks, the random module generates pseudo-random numbers, and the datetime module manages date and time operations. Each module is accompanied by example code snippets to illustrate their usage.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

8_time, random, datetime

The document provides an introduction to the time, random, and datetime modules in Python, detailing their functionalities and key functions. It explains how the time module handles time-related tasks, the random module generates pseudo-random numbers, and the datetime module manages date and time operations. Each module is accompanied by example code snippets to illustrate their usage.

Uploaded by

Arif Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Introduction to time, random,

datetime in Python
Learning objective
• What is a time module?
• Functions provided by time module
• Random module
• Functions provided by random module
• Datetime module
• Functions provided by datetime module
time module
• In Python, the time, random, and datetime (for date) modules are
part of the standard library and provide functionalities related to
time, random numbers, and date/time operations, respectively.

• The time module provides functions that deal with time-related


tasks.
• It allows you to work with time values, sleep or pause the
execution of your program, and convert between different
representations of time.
time module
time() Function: Returns the current time in seconds since epoch /
era (January 1, 1970).

import time
current_time = time.time()
print(current_time)

Unix timestamp, a float representing the precise number of


seconds since the epoch.
time() benefits
This is useful for measuring time duration (e.g., to time how long a
process takes), Logging timestamps, Handling time-based calculations.

import time
start_time = time.time() # Record start time
# Some code that you want to time

end_time = time.time() # Record end time


print("Elapsed time:", end_time - start_time, "seconds")
time module
Ctime() function: Converts a time in seconds since the epoch to a
string representing the local time.
Example:

import time
current_time = time.time()
local_time_string = time.ctime(current_time)
print(local_time_string)
time module
• sleep() Function:
• Suspends the execution of the current thread for a specified
number of seconds.

import time
print("This is printed immediately.")
time.sleep(5)
print("This is printed after 5 seconds.")
time module
• gmtime() and localtime() Functions
• Convert a time in seconds since the epoch to a struct_time in UTC or
local time.

import time
current_time = time.time()
utc_time = time.gmtime(current_time)
local_time = time.localtime(current_time)
print("UTC Time:", utc_time)
print("Local Time:", local_time)
time module
• Format a struct_time or time in seconds since the epoch as a
string.

import time
current_time = time.time()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(current_time))
print("Formatted Time:", formatted_time)
time module
• These are just a few examples of the functionalities provided by
the time module.

• It's a versatile module that can be useful in various scenarios,


especially when dealing with time-related operations in your
Python programs.
random module
• The random module in Python provides functions for generating pseudo-
random numbers.

• These functions are useful in a variety of applications, such as


simulations, games, and statistical sampling.

random() Function: Returns a random floating-point number in the range


[0.0, 1.0].

import random
random_number = random.random()
print(random_number)
random module
• randint(a, b) Function:
• Returns a random integer in the range [a, b](inclusive).

import random
random_integer = random.randint(1, 10)
print(random_integer)
random module
• choice(seq) Function:
• Returns a random element from the given sequence (list, tuple, or
string).

import random
fruits = ['apple', 'banana', 'orange', 'grape']
random_fruit = random.choice(fruits)
print(random_fruit)
random module
• shuffle(seq) Function:
• Randomly shuffles the elements of the given sequence in place.

import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
random module
• sample(population, k) Function:
• Returns a k-length list of unique elements chosen randomly from
the given population.

import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_samples = random.sample(numbers, 3)
print(random_samples)
random module
• uniform(a, b) Function:
• Returns a random floating-point number in the range (a, b).
• These functions can be useful when you need to introduce
randomness into your programs or simulate scenarios where
unpredictable values are needed.
• It's important to note that the numbers generated by these
functions are pseudorandom, meaning they are generated by
algorithms and not truly random.

import random
random_float = random.uniform(1.0, 2.0)
print(random_float)
datetime module
• In Python, the date module is part of the datetime module, which
provides classes for working with dates and times.

• The date class specifically represents dates (year, month, and


day) and allows various operations related to dates.

• Here are some key aspects of the date module:


datetime module
• Importing the Module:
• To use the date module, you need to import the datetime module,
as it is part of it.
from datetime import date

• Creating Date Objects:


• You can create a date object representing a specific date using the
date class constructor. The syntax is as follows:
my_date = date(year, month, day)
datetime module
from datetime import date
# Creating a date object for December 25, 2022
christmas = date(2022, 12, 25)
print(christmas)

• Current Date:
• You can obtain the current date using the today() method.
from datetime import date
current_date = date.today()
print(current_date)
date attributes
Date Attributes:
Once you have a date object, you can access its attributes
such as year, month, and day

from datetime import date


christmas = date(2022, 12, 25)
print(christmas.year)
print(christmas.month)
print(christmas.day)
date Operations
• You can perform various operations on date objects, such as finding the difference
between two dates.

from datetime import datetime


date1 = datetime(2024, 10, 28)
date2 = datetime(2024, 11, 7)
# Calculate difference
difference = date2 - date1
print("Difference:", difference)
# Access the number of days in the difference
print("Days between dates:", difference.days)

• These are some basic functionalities provided by the datetime module for working
with dates in Python.
You must have learnt:
• What is a time module?
• Functions provided by time module
• Random module
• Functions provided by random module
• Datetime module
• Functions provided by datetime module

You might also like