The time’s Python time() Python method returns the time in seconds since the epoch in UTC as a floating-point number. Although the time is always supplied as a floating-point number, not all systems give time with an accuracy greater than one second. While this function generally provides non-decreasing values, it may return a lower value if the system clock has been reset between the two calls.
The epoch is the starting point for time and is platform-dependent. The epoch, in this case, refers to January 1, 1970, 00:00:00 (UTC) on Windows and most Unix systems, and leap seconds are not included in the time in seconds since the epoch. We can utilize time to determine the epoch for a specific platform.gmtime(0).
Python time.time() Syntax
The syntax for the time() method is as follows:
This method is responsible for returning the time in seconds since the epoch, in UTC, as a floating-point number.
The time() method is demonstrated in the following example.
#!/usr/bin/python import time print("time.time(): %f " % time.time()) print(time.localtime( time.time() )) print(time.asctime( time.localtime(time.time()) ))
Upon running the above program, we get the following output:
time.time() in Python
The time() function returns the number of seconds that have passed since the beginning of time. The epoch for Unix systems is January 1, 1970, at 00:00:00 UTC (the point where time begins).
import time time_in_seconds = time.time() print("Number of seconds since epoch =", time_in_seconds )
time.ctime() in Python
The time.ctime() function accepts a string representing local time as an argument and returns it as a string.
import time # the number of seconds passed since epoch number_of_seconds = 1545925769.9618232 time_locally = time.ctime(number_of_seconds) print("Time Locally is:", time_locally)
If you run the code displayed prior, you’ll get something like this:
sleep() in Python
The sleep() function suspends (delays) the current thread’s execution for the specified amount of time.
import time print("Information that is printed instantly.") time.sleep(2.4) print("This is information that is printed after 2.4 seconds.")
Let’s take a quick look at the time.struct time class before moving on to other time-related functions.
Several functions in the time module, such as gmtime() and asctime(), either take or return the time.struct_time object. An example of a time.struct_time object is shown below.
time.struct_time(tm_year=2022, tm_mon=12, tm_mday=27, tm_hour=6, tm_min=35, tm_sec=17, tm_wday=3, tm_yday=361, tm_isdst=0)
Both indices and attributes are used to access the values (elements) of the time.struct time object.
time.localtime() for Python
The localtime() function accepts an input of the number of seconds since the epoch and returns struct_time in local time.
import time resultant_time = time.localtime(1652799180.0116804) print("The resultant time is :", resultant_time) print("\nyear:", resultant_time.tm_year) print("tm_hour:", resultant_time.tm_hour)
The following are the outcomes of running the application:
The value returned by time() is utilized if no argument or None is supplied to localtime().
time.gmtime() in Python
The gmtime() function accepts an input of the number of seconds since epoch and returns struct_time in UTC.
import time time_results = time.gmtime(1652799180.0116804) print("resultant time is:", time_results) print("\nyear:", time_results.tm_year) print("tm_hour:", time_results.tm_hour)
The following are the outcomes of running the application:
If gmtime() is called with no arguments or None, the value returned by time() is utilized.
time.mktime() in Python
The mktime() method takes struct_time (or a tuple of 9 elements corresponding to struct_time) as an argument and returns the number of seconds since the epoch in local time. It’s essentially the inverse of localtime().
import time time_now_is = (2022, 12, 28, 8, 44, 4, 4, 362, 0) time_locally_is = time.mktime(time_now_is) print("The Local time is:", time_locally_is)
The following example demonstrates the relationship between mktime() and localtime().
import time number_of_seconds_elapsed = 1652799180.0116804 # returns struct_time time_now_is = time.localtime(number_of_seconds_elapsed) print("time now is: ", time_now_is) # returns the number of seconds from struct_time count_of_seconds = time.mktime(time_now_is) print("\s:", count_of_seconds)
When you run the program, you should get something like this:
time.asctime() in Python
The asctime() function accepts struct time as an input and returns a string representing it.
Consider the following scenario:
import time time_in_seconds = (2022, 12, 28, 8, 44, 4, 4, 362, 0) time_now_is = time.asctime(time_in_seconds) print("The time result is:", time_now_is)
The following are the outcomes of running the application:
time.strftime() in Python
The strftime() method takes an argument of struct_time (or a tuple matching to it) and returns a string representing it based on the format code used. For instance,
import time the_named_tuple = time.localtime() # get struct_time the_time_string = time.strftime("%m/%d/%Y, %H:%M:%S", the_named_tuple) print(the_time_string)
Upon running the program, you should get something like this:
The following are sample format codes, %Y, %m, %d, %H, etc.
%Y - year [0001,..., 2020, 2021,..., 9999] %m - month [01, 02, ..., 11, 12] %d - day [01, 02, ..., 30, 31] %H - hour [00, 01, ..., 22, 23 %M - minutes [00, 01, ..., 58, 59] %S - second [00, 01, ..., 58, 61]
time.strptime() in Python
The strptime() function returns struct time after parsing a string representing time.
import time the_time_string_is = "16 May, 2022" time_result_is = time.strptime(the_time_string_is, "%d %B, %Y") print(time_result_is)
On running the application, you’ll get the following results:
Example: Program for demonstrating the time.time() method
# first, import the module 'time' import time # then, fetch the epoch obj_var = time.gmtime(0) epoch_var = time.asctime( obj_var) print("The epoch variable is:", epoch_var) # Fetch the given time in terms of seconds # as from the specified epoch time_in_sec = time.time() # Printing the specified time print("Time in seconds since the epoch:", time_in_sec)
Example: Program for calculating the number of seconds elapsed between two specified dates
# program for demonstrating time.time() method in Python # start by importing the module 'time' import time # specifying the first Date date_one_var = "17 May 2022 00:00:00" # Specifying the second Date # This is the current_date date_two_var = "22 May 2022 00:00:00" # Parsing the respective date strings # and converting it in the # time.struct_time object by using # the method 'time.strptime() ' obj_one_ = time.strptime(date_one_var, "% d % b % Y % H:% M:% S") obj_two_ = time.strptime(date_two_var, "% d % b % Y % H:% M:% S") # Getting the time in terms of seconds count # from the commencement of the epoch # for both objects in time.struct_time time_one_var = time.mktime(obj1) time_two_var = time.mktime(obj2) print("The first Date is:", time.asctime(obj_one_)) print("The second Date is:", time.asctime(obj _two_)) # The count of the seconds between the first date and the second date seconds_count = time_two_var - time_one_var print("Seconds between date 1 and date 2 is % f seconds" % seconds_count)
Example: The use of time() with localtime() in printing the current date and time
In the previous example, the date and time data are printed as a string, which is the default output of the ctime() method. However, you must use another method called localtime() with the time() method if you wish to read each component of the data and time values and output each value in a particular format. The output of the time() method is passed to the localtime() method, which provides a structure containing date and time values that are read individually.
The following example explains how to use the time() and localtime() methods to read and output different bits of current data and time. The time module is imported at the scripts’ beginning to use the time() and localtime() methods.
The output of the time() method is saved in curTime. While the result of the localtime() method is saved in localTime. To examine the structural output of the localTime variable, its value is printed.
Then, based on the numeric value set in the output of the localtime() method, a list of months and a list of weekday variables are declared to represent the names of the month and weekday. Finally, the script will generate four formats of formatted data and time outputs.
# Import time module import time #In seconds, read the current time. curTime=time.time() # Use localtime to read data and time values () localTime = time.localtime(curTime) # Print the results of the localtime() command print("localtime() produces the following result :\n",localTime) # Definition of the month list. months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] # Make a list of weekdays. weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] print("\n The following are the formatted outputs: ") # The current date should be printed as follows print("\nDate :" ,localTime.tm_mday, months[localTime.tm_mon-1], localTime.tm_year) # Display the current time. print("\nTime : %dh:%dm:%ds" %(localTime.tm_hour,localTime.tm_min,localTime.tm_sec)) # Print the name of the current workday. print("\nThe day today is: " , weekdays[localTime.tm_wday]) # Print the current year's date. print("\nToday is %d days of the year" %localTime.tm_yday)
Example: Using time(), localtime() and strftime() show date and time
The strftime() function in Python may read date and time values using several types of format codes. The following script uses the time(), localtime(), and strftime() methods to generate more particular formatted date and time values than the previous two examples. To use the three ways indicated above, the time module is loaded at the beginning of the script.
The output of the time() function is first supplied as an argument to the localtime() method, and then the strftime() method uses the output of the localtime() method along with format codes to generate various types of outputs.
In contrast to other programming languages (‘1st’, ‘2nd’, ‘3rd’, and ‘th’), there is no direct format code in Python to append suffix with the day. A suffix function is defined to add a suffix to the date’s daily value.
# Module for importing time import time # Take note of the current date and time. currentDT = time.localtime(time.time()) # Read the month's issue. day = int(time.strftime("%d", currentDT)) # Create a function that sets the day suffix. def suffix(day): if ((day > 3 and day <= 20) or (day > 23 and day <= 30)): suffix = "th" else: suffix = ["st", "nd", "rd"][day % 10 - 1] return suffix # Showing a short date print("Short Date :", time.strftime("%d-%m-%Y", currentDT)) # Display long date print(time.strftime("Long Date : %A, %d" + suffix(day) +" %B %Y", currentDT)) # Display short time print(time.strftime("Short Time : %H:%M:%S",currentDT)) # Displaying a long time print(time.strftime("Long Time : %I:%M:%S %p", currentDT))
Example: Using time() with ctime() in printing the current date and time
# Importing time and ctime from the time module from time import time, ctime # In seconds, read the current data and time. DateTime_NOW = time() # Printing the resultant output from time() print("\nThe resultant time() output is:",DateTime_NOW) # In a comprehensible format, print the current date and time. print('\nThe date Today is: ',ctime(DateTime_NOW))
The time() method returns a value in seconds with an unreadable floating-point number. The ctime() method is used to display the time() method’s return value in an understandable way. To utilize the time() and ctime() methods, import time and ctime from the time module at the beginning of the script. Using the time() method, the script will store the current date and time value in seconds in the variable DateTime_NOW. The value of DateTime_NOW will then be displayed. The ctime() method takes the value of this variable as an argument and converts it to a human-readable format before printing it.
We’ve looked at the time module in-depth in this tutorial. With the help of examples, we have learned how to use the many time-related functions defined in the time module. To handle time-related tasks, Python has a module called time. To use the functions defined in the module, we must first import them.