Python time Module with Examples

Python time Module: In this tutorial, we are going to learn about the time module with its methods and examples in Python programming language. By Bipin Kumar Last updated : June 21, 2023

Python time Module

The time module is a built-in module in Python and it has various functions that require to perform more operations on time. This is one of the best modules in Python that used to solve various real-life time-related problems. To use the time module in the program, initially, we have to import the time module.

This module begins the recording time from the epoch. Epoch means time in history and it begins on 1st January 1970.

Most Useful Methods of Python time Module

time() Method

This function returns the number of the second count since the epoch.

Example

# Importing the module
import time

s=time.time()
print('Total seconds since epoch:',s)

Output

Total seconds since epoch: 1576083939.5877264

ctime() Method

This function of the time module takes second as an argument and return time till the mentioned seconds.

Example

# Importing the module
import time

s=1575293263.821702
Current_time=time.ctime(s)
print('current time since epoch:',Current_time)

Output

current time since epoch: Mon Dec  2 13:27:43 2019

sleep() Method

This function is used to stay the program execution for the time given in the arguments of this function.

Example

# Importing the module
import time

print('Execution starting time:',time.ctime())
time.sleep(5)
print('After execution time:',time.ctime())

Output

Execution starting time: Wed Dec 11 17:10:47 2019
After execution time: Wed Dec 11 17:10:52 2019

strftime() Method

This function takes an argument and returns a string based on the format code.

Example

# Importing the module
import time

Current_time=time.localtime() 

time_in_format=time.strftime("%m/%d/%Y, %H:%M:%S",Current_time)

print('time in specific format since epoch:',time_in_format)

Output

time in specific format since epoch: 12/11/2019, 17:12:47

asctime() Method

This function takes a tuple of length nine as an argument and returns a string.

Example

# Importing the module
import time

t=(2019,12,2,5,30,2,7,365,0)
r=time.asctime(t)
print("Time and date in a specific format:",r)

Output

Time and date in a specific format: Mon Dec  2 05:30:02 2019

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.