Python

How to use python time.time() method

Time-related tasks are done in python by using the time module. The time value can be displayed in various ways by using this module. time.time() method of this module is used to read the time in seconds based on epoch convention. According to epoch, time calculation starts from the date, January 1, 1970, 00:00:00 (UTC) and It supports the date and time up to the year 2038 for the most of the operating system. time() method of time module returns the time in seconds as a floating-point number. How this method can be used with other necessary methods of time module to display the time value in different formats is explained in this tutorial.

Syntax:

time.time()

This method has no argument and it returns the times in seconds since the epoch starting time is a floating-point number. Different uses of time() method are shown in the next part of the tutorial.

Example-1: Use of time()  with ctime() to print current date and time

It is mentioned before that time() method returns the value in seconds and it is a floating-point number that is not readable. ctime() method is used here to represent the return value of time() method in a readable format. Import time and ctime from the time module at the beginning of the script to use time() and ctime() methods. The script will store the current date and time value in seconds in the variable named current_DateTime by using the time() method. Next, the value of current_DateTime will be printed. The value of this variable is passed as the argument of the ctime() method to convert it into human-readable format and print the value.

# Import time and ctime from time module
from time import time, ctime

# Read the current data and time in seconds
current_DateTime = time()

# Print the output of time()
print("\nThe output of time():",current_DateTime)

# Print the current date and time in readable format
print('\nToday is: ',ctime(current_DateTime))

Output:

The following output will appear after running the script.

Example-2: Use of time() with localtime() to print current date and time separately

The date and time values are printed as a string in the previous example that is the default output of the ctime() method. But if you want to read each part of data and time values and print each value by using custom format then you have to use another method named localtime() with time() method. localtime() method takes the output of time() method as an argument and returns a structure of date and time values that can read separately. The following example shows how you can read and print different parts of current data and time by using time() and localtime() methods. time module is imported at the beginning of the script to use time() and localtime() methods. The output of time() method is stored in the variable, curTime and the output of localtime() method is stored in the variable localTime. The value of localTime variable is printed to see the structural output of this variable. Next, a list of months and a list of weekdays variables are declared to represent the names of the month and weekday based on the numeric value set in the output of the localtime() method. Lastly, the script will generate the four types of formatted outputs of data and time.

#!/usr/bin/env python3
# Import time module
import time

# Read current time in seconds
curTime=time.time()

# Read data and time values using localtime()
localTime = time.localtime(curTime)

# Print the output of the localtime()
print("The output of localtime() is :\n",localTime)

# Define the list of months
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']

# Define the list of week days
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print("\nThe formatted outputs are given below:")

# Print the current date
print("\nDate :" ,localTime.tm_mday, months[localTime.tm_mon-1], localTime.tm_year)

# Print the current time
print("\nTime : %dh:%dm:%ds" %(localTime.tm_hour,localTime.tm_min,localTime.tm_sec))

# Print the current weekday name
print("\nToday is " , weekdays[localTime.tm_wday])

# Print the day of the year
print("\nToday is %d days of the year"  %localTime.tm_yday)

Output:

The following output will appear after running the script.

Example-3: Use of time() with localtime() and strftime() to print date and time

There is another method in python to read date and time values using different types of format codes which is called strftime() method. time(), localtime() and strftime() methods are used in the following script to generate more specific formatted date and time values than the previous two examples. time module is imported at the beginning of the script to use three methods mentioned here. At first, the output of time() method is passed as the argument of localtime() method, and next, strftime() method uses the output of localtime() method with format codes in various ways to generate different types of outputs. There is no direct format code in python to add suffix with the day like other programming languages (‘1st’, ‘2nd’, ‘3rd’, and ‘th’). Here, a function named suffix is defined to add suffix with the day value of the date.

#!/usr/bin/env python3
# Import time module
import time

# Read the current date and time
currentDT = time.localtime(time.time())

# Read dthe ay of the month
day = int(time.strftime("%d", currentDT))

# Define function to set 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

# Display 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))

# Display long time
print(time.strftime("Long Time : %I:%M:%S %p", currentDT))

Output:

The following output will generate after running the script.

Conclusion:

Many time-related methods exist in the time module of python. The uses of time() method with the other two useful time methods of python are shown in this tutorial. I hope, this tutorial will help the readers to learn the use of time() method.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.