Open In App

Time Functions in Python | Set 1 (time(), ctime(), sleep()…)

Last Updated : 04 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python has defined a module, “time” which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python.

Operations on Time in Python 

Python time.time() Function

Python time() function is used to count the number of seconds elapsed since the epoch

Python3




# Python code to demonstrate the working of
# time()
 
#  importing "time" module for time operations
import time
 
# using time() to display time since epoch
print ("Seconds elapsed since the epoch are : ",end="")
print (time.time())


Python time.gmtime() Function

Python gmtime() function returns a structure with 9 values each representing a time attribute in sequence. It converts seconds into time attributes(days, years, months etc.) till specified seconds from the epoch. If no seconds are mentioned, time is calculated till the present. The structure attribute table is given below. 

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 
 7        tm_yday     1 to 366
 8        tm_isdst    -1, 0, 1 where -1 means Library determines DST

Python3




# Python code to demonstrate the working of gmtime()
import time
# using gmtime() to return the time attribute structure
print ("Time calculated acc. to given seconds is : ")
print (time.gmtime())


Output: 

Time calculated acc. to given seconds is : 
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=2,
tm_hour=7, tm_min=12, tm_sec=31, tm_wday=1, 
tm_yday=215, tm_isdst=0)

Python time.asctime() and time.ctime() Function

Python time.asctime() function takes a time-attributed string produced by gmtime() and returns a 24-character string denoting time.Python time.ctime() function returns a 24-character time string but takes seconds as an argument and computes time till mentioned seconds. If no argument is passed, time is calculated till the present.

Python3




# Python code to demonstrate the working of
# asctime() and ctime()
 
#  importing "time" module for time operations
import time
 
# initializing time using gmtime()
ti = time.gmtime()
 
# using asctime() to display time acc. to time mentioned
print ("Time calculated using asctime() is : ",end="")
print (time.asctime(ti))
 
 
# using ctime() to display time string using seconds
print ("Time calculated using ctime() is : ", end="")
print (time.ctime())


Output: 

Time calculated using asctime() is : Tue Aug  2 07:47:02 2016
Time calculated using ctime() is : Tue Aug  2 07:47:02 2016

Python time.sleep() Function

This method is used to halt the program execution for the time specified in the arguments.

Python3




# Python code to demonstrate the working of
# sleep()
 
#  importing "time" module for time operations
import time
 
# using ctime() to show present time
print ("Start Execution : ",end="")
print (time.ctime())
 
# using sleep() to hault execution
time.sleep(4)
 
# using ctime() to show present time
print ("Stop Execution : ",end="")
print (time.ctime())


Output: 

Start Execution : Tue Aug  2 07:59:03 2016
Stop Execution : Tue Aug  2 07:59:07 2016

Python time.mktime() Function

In this example, we have created a struct_time object with a tuple of values for each of its fields then we have passed the object to the time.mktime() to convert it to a floating-point number representing the number of seconds since the Unix epoch.

Python3




import time
 
# Create a struct_time object representing a date and time
my_time = time.strptime("2023-05-10 14:30:00",
                        "%Y-%m-%d %H:%M:%S")
 
# Convert the struct_time object to a floating-point number
seconds_since_epoch = time.mktime(my_time)
 
print("Seconds since epoch:", seconds_since_epoch)


Output:

Seconds since epoch: 1683709200.0

Python time.localtime() Function

In this example, we call time.localtime() with no argument to get the current local time as a struct_time.

Python3




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


Output:

time.struct_time(tm_year=2023, tm_mon=5, tm_mday=10, 
tm_hour=12, tm_min=42, tm_sec=51, tm_wday=2, tm_yday=130, tm_isdst=0)

Python time.strftime() Function

It takes a format string as its first argument, which specifies the desired format of the output string.

Python3




import time
now = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
print(formatted_time)


Output:

2023-05-10 13:42:04


Similar Reads

Python - time.ctime() Method
Python time.ctime() method converts a time in seconds since the epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). Current time is returned by localtime() is used when the time tuple is not present. Syntax: time.ctime([ sec ]) Parameter: sec: number of seconds to be converted into string representation. Example 1: L
2 min read
Python | Pandas Timestamp.ctime
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.ctime() function return the time in string format. The format of the returned string object is based on ctime() style.
2 min read
ctime() Function Of Datetime.date Class In Python
The ctime() function is used to return a string containing the date and time. Syntax: ctime() Parameters: This function does not accept any parameter. Return values: This function returns a string containing the date and time. The format of the string representation: The string is of 24-character length.Week is printed as a three-letter word.Sun, M
2 min read
time.sleep() in Python
Python time sleep() function suspends execution for the given number of seconds. Syntax of time sleep() Syntax : sleep(sec) Parameters : sec : Number of seconds for which the code is required to be stopped. Returns : VOID. Sometimes, there is a need to halt the flow of the program so that several other executions can take place or simply due to the
4 min read
Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
3 min read
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
2 min read
Time Functions in Python | Set-2 (Date Manipulations)
Some of Time Functions are discussed in Set 1 Date manipulation can also be performed using Python using "datetime" module and using "date" class in it. Operations on Date : 1. MINYEAR :- It displays the minimum year that can be represented using date class. 2. MAXYEAR :- It displays the maximum year that can be represented using date class. # Pyth
2 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Article Tags :
Practice Tags :