Time Functions in Python?

PythonServer Side ProgrammingProgramming

Python provides library to read, represent and reset the time information in many ways by using “time” module. Date, time and date time are an object in Python, so whenever we do any operation on them, we actually manipulate objects not strings or timestamps.

In this section we’re going to discuss the “time” module which allows us to handle various operations on time.

The time module follows the “EPOCH” convention which refers to the point where the time starts. In Unix system “EPOCH” time started from 1 January, 12:00 am, 1970 to year 2038.

To determine the EPOCH time value on your system, just type below code -

>>> import time
>>> time.gmtime(0)

Output

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

Tick in python?

A tick refers to a time interval which is a floating-point number measured as units of seconds. Sometime we get time as Daylight Saving Time(DST), where the clock moves 1 hour forward during the summer time, and back again in the fall.

Most common functions in Python Time Module -

1. time.time() function

The time() is the main function of the time module. It measures the number of seconds since the epoch as a floating point value.

Syntax

time.time()

Program to demonstrate above function:

import time
print("Number of seconds elapsed since the epoch are : ", time.time())

Output

Number of seconds elapsed since the epoch are : 1553262407.0398576

We can use python time function to calculate the elapsed Wall-clock time between two points.

Below is the program to calculate Wall clock time:

import time
start = time.time()
print("Time elapsed on working...")
time.sleep(0.9)
end = time.time()
print("Time consumed in working: ",end - start)

Output

Time elapsed on working...
Time consumed in working: 0.9219651222229004

2. time.clock() function

The time.clock() function return the processor time. It is used for performance testing/benchmarking.

Syntax

time.clock()

The clock() function returns the right time taken by the program and it more accurate than its counterpart.

Let’s write a program using above two time functions (discussed above) to differentiate:

import time
template = 'time()# {:0.2f}, clock()# {:0.2f}'
print(template.format(time.time(), time.clock()))
for i in range(5, 0, -1):
   print('---Sleeping for: ', i, 'sec.')
time.sleep(i)
print(template.format(time.time(), time.clock())
)

Output

time()# 1553263728.08, clock()# 0.00
---Sleeping for: 5 sec.
time()# 1553263733.14, clock()# 5.06
---Sleeping for: 4 sec.
time()# 1553263737.25, clock()# 9.17
---Sleeping for: 3 sec.
time()# 1553263740.30, clock()# 12.22
---Sleeping for: 2 sec.
time()# 1553263742.36, clock()# 14.28
---Sleeping for: 1 sec.
time()# 1553263743.42, clock()# 15.34

3. time.ctime() function

time.time() function takes the time in “seconds since the epoch” as input and translates into a human readable string value as per the local time. If no argument is passed, it returns the current time.

import time
print('The current local time is :', time.ctime())
newtime = time.time() + 60
print('60 secs from now :', time.ctime(newtime))

Output

The current local time is : Fri Mar 22 19:43:11 2019
60 secs from now : Fri Mar 22 19:44:11 2019

4. time.sleep() function

time.sleep() function halts the execution of the current thread for the specified number of seconds. Pass a floating point value as input to get more precise sleep time.

The sleep() function can be used in situation where we need to wait for a file to finish closing or let a database commit to happen.

import time
# using ctime() to display present time
print ("Time starts from : ",end="")
print (time.ctime())
# using sleep() to suspend execution
print ('Waiting for 5 sec.')
time.sleep(5)
# using ctime() to show present time
print ("Time ends at : ",end="")
print (time.ctime())

Output

Time starts from : Fri Mar 22 20:00:00 2019
Waiting for 5 sec.
Time ends at : Fri Mar 22 20:00:05 2019

5. time.struct_time class

The time.struct_time is the only data structure present in the time module. It has a named tuple interface and is accessible via index or the attribute name.

Syntax

time.struct_time

This class is useful when you need to access the specific field of a date.

This class provides number of functions like localtime(), gmtime() and return the struct_time objects.

import time
print(' Current local time:', time.ctime())
t = time.localtime()
print('Day of month:', t.tm_mday)
print('Day of week :', t.tm_wday)
print('Day of year :', t.tm_yday)

Output

Current local time: Fri Mar 22 20:10:25 2019
Day of month: 22
Day of week : 4
Day of year : 81

6. time.strftime() function

This function takes a tuple or struct_time in the second argument and converts to a string as per the format specified in the first argument.

Syntax

time.strftime()

Below is the program to implement time.strftime() function -

import time
now = time.localtime(time.time())
print("Current date time is: ",time.asctime(now))
print(time.strftime("%y/%m/%d %H:%M", now))
print(time.strftime("%a %b %d", now))
print(time.strftime("%c", now))
print(time.strftime("%I %p", now))
print(time.strftime("%Y-%m-%d %H:%M:%S %Z", now))

Output

Current date time is: Fri Mar 22 20:13:43 2019
19/03/22 20:13
Fri Mar 22
Fri Mar 22 20:13:43 2019
08 PM
2019-03-22 20:13:43 India Standard Time

Check timezone in python

There are two time-properties which give you the timezone info -

1. time.timezone

It returns the offset of the local (non-DST) timezone in UTC format.

>>> time.timezone
-19800

2. time.tzname – It returns a tuple containing the local non-DST and DST time zones.

>>> time.tzname
('India Standard Time', 'India Daylight Time')
raja
Published on 30-Apr-2019 12:29:08
Advertisements