Python Time module provides functions for working with times, and for converting between representations. Using this module it is possible to run programs without our supervision as the built-in time module allows our Python programs to read the system clock for the current time. Thus we can use our computer’s clock to schedule programs to run code at some specified time and date or at regular intervals.
A given date and time can either be represented as a floating point value (the number of seconds since a reference date, usually January 1st, 1970), or as a time tuple. This module follows the EPOCH convention which refers to the point where the time starts. It supports the dates and times from the epoch to the year 2038.
Many of Python's time functions handle time as a tuple of 9 numbers, as shown below:
Index Field Values
0 4-digit year 2008
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61 (60 or 61 are leap-seconds)
6 Day of Week 0 to 6 (0 is Monday)
7 Day of year 1 to 366 (Julian day)
8 Daylight
savings -1, 0, 1, -1 means library determines DST
The above tuple is equivalent to struct_time structure. This structure has following attribute:
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 (0 is Monday)
7 tm_yday 1 to 366 (Julian day)
8 tm_isdst -1, 0, 1, -1 means library determines DST
Let's start using this module now and do the following:
Getting the current time
The Unix epoch is a time reference commonly used in programming: 12 am on January 1, 1970, Coordinated Universal Time (UTC). The time.time() function returns the number of seconds since that moment as a float value. This number is called an epoch timestamp. To get the current time we will use the time.time() function as shown in the following code:
import time
print(time.time())
This program gives the following output:
1545801454.260125
------------------
(program exited with code: 0)
Press any key to continue . . .
The return value is how many seconds have passed between the Unix epoch and the moment time.time() was called.
To translate a time instant from a seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all nine items valid. See the code below:
import time
print(time.localtime(time.time()))
This program gives the following output:
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=10, tm_min=59, tm_
sec=8, tm_wday=2, tm_yday=360, tm_isdst=0)
------------------
(program exited with code: 0)
Press any key to continue . . .
There is this function time.gmtime() which also returns a struct_time object and can be used to determine the EPOCH value on our system as shown below:
import time
print(time.gmtime(0))
This program gives the following 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)
------------------
(program exited with code: 0)
Press any key to continue . . .
The tuple returned by localtime and gmtime contains (year, month, day, hour, minute, second, day of week, day of year, daylight savings flag), where the year number is four digits, the day of week begins with 0 for Monday, and January 1st is day number 1.
Other useful functions in the time module
The most used functions and the data structure of the time module in Python are as follows:
- time.time()
- time.clock()
- time.ctime()
- time.sleep()
- time.struct_time class
- time.strftime()
1. time.time()
Epoch timestamps can be used to profile code, that is, measure how long a piece of code takes to run. If you call time.time() at the beginning of the code block you want to measure and again at the end, you can subtract the first timestamp from the second to find the elapsed time between those two calls.See the code below:
import time
def addnumbers():
result =1
for num in range(1,100000):
result = result+num
return result
start_adding = time.time()
total = addnumbers()
finish_adding = time.time()
print('The addition of first 100000 numbers is ' + str(total))
print('\nThe addition took ' + str(finish_adding - start_adding) +' seconds to complete')
This program gives the following output:
The addition of first 100000 numbers is 4999950001
The addition took 0.00700068473815918 seconds to complete
------------------
(program exited with code: 0)
Press any key to continue . . .
2. Time.Sleep() Function
The time.sleep() Function is used to pause a program for a while. To use this function in your program just call it and pass the number of seconds a program should pause as argument. See the program below:
import time
for t in range(5):
print('running')
time.sleep(1)
print('paused')
time.sleep(1)
This program gives the following output:
running
paused
running
paused
running
paused
running
paused
running
paused
------------------
(program exited with code: 0)
Press any key to continue . . .
The for loop will print running, pause for one second , printpaused, pause for one second , print running, pause, and so on until running and paused have each been printed five times.
3. Time.Clock() Function
The time.clock() returns the processor clock time. The time.time() function computes the wall clock time. We can use time.clock() for performance testing/benchmarking and time.time() to schedule something.
The output of the clock() function reflects the right time taken by the program. And it is more accurate than its counterpart. However, its exact behavior may vary with the OS you are using. It could return process time ignoring the time to sleep. And in some cases, it could count the time elapsed even when the process was inactive.
While time.time behaves the same on Unix and on Windows, time.clock has different meanings. On Unix, time.clock returns the current processor time expressed in seconds, i.e., the CPU time it takes to execute the current thread so far. While on Windows, it returns the wall-clock time expressed in seconds elapsed since the first call to this function, based on the Win32 function QueryPerformanceCounter. Another difference between time.time and time.clock is that time.time could return a lower-value than a previous call if the system clock has been set back between the two calls while time.clock always return non-decreasing values.
The following program shows the usage of both time.clock() and time.time():
import time
print(time.time(), time.clock())
time.sleep(1)
print(time.time(), time.clock())
This program gives the following output on Windows platform:
1545806902.7569518 6.621319456813437e-07
1545806903.7750099 1.0177345420331292
------------------
(program exited with code: 0)
Press any key to continue . . .
Both time.time() and time.clock() show that the wall-clock time passed approximately one second. The time.clock() returns the wall-clock time with a higher precision than time.time()
4. The time.Ctime() function
It takes the time in “seconds since the epoch” as input and translates into a human readable string value as per the local time. In case of no argument, it calls the time() function and returns the current time. The length of the string returned by time.ctime() is 24 characters.The syntax is
time.ctime(seconds)
The following program shows the usage of time.ctime():
import time
print('The current time is :', time.ctime())
newtime = time.time() + 10
print('10 secs from now :', time.ctime(newtime))
This program gives the following output:
The current time is : Wed Dec 26 12:25:20 2018
10 secs from now : Wed Dec 26 12:25:30 2018
------------------
(program exited with code: 0)
Press any key to continue . . .
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.
This class is useful when you need to access the specific fields of a date (year, month, etc.). There are a no. of functions (like localtime(), gmtime()) that return the struct_time objects. See the program below:
import time
print(time.localtime(time.time()))
This program gives the following output:
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=12, tm_min=31, tm_sec=17, tm_wday=2, tm_yday=360, tm_isdst=0)
------------------
(program exited with code: 0)
Press any key to continue . . .
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. If t is not present, then it calls the localtime() to use the current date. The syntax is time.strftime(format[, t])
See the example below:
import time
at_present = time.localtime(time.time())
print(time.asctime(at_present))
print(time.strftime("%y/%m/%d %H:%M", at_present))
print(time.strftime("%a %b %d", at_present))
print(time.strftime("%c", at_present))
print(time.strftime("%I %p", at_present))
print(time.strftime("%Y-%m-%d %H:%M:%S %Z", at_present))
This program gives the following output:
Wed Dec 26 12:35:28 2018
18/12/26 12:35
Wed Dec 26
Wed Dec 26 12:35:28 2018
12 PM
2018-12-26 12:35:28 India Standard Time
------------------
(program exited with code: 0)
Press any key to continue . . .
On some platforms, the time module contains a strptime function, which is pretty much the opposite of strftime. Given a string and a pattern, it returns the corresponding time tuple.
The time.strptime function is currently only made available by Python if it’s provided by the platform’s C libraries. Windows platform don’t have a standard implementation of strftime.
The output of functions in time module usually contains float values with many digits after the decimal. To make these values easier to work with, we can shorten them with Python’s built-in round() function, which rounds a float to the precision you specify.
Just pass in the number you want to round, plus an optional second argument representing how many digits after the decimal point you want to round it to. If you omit the second argument, round() rounds your number to the nearest whole integer. See the code below:
import time
at_present = time.time()
print(at_present)
print(round(at_present))
print(round(at_present,2))
print(round(at_present,4))
at_present = time.time()
print(at_present)
print(round(at_present))
print(round(at_present,2))
print(round(at_present,4))
This program gives the following output:
1545809783.2086208
1545809783
1545809783.21
1545809783.2086
------------------
(program exited with code: 0)
Press any key to continue . . .
1545809783
1545809783.21
1545809783.2086
------------------
(program exited with code: 0)
Press any key to continue . . .
After importing time and storing time.time() in at_present , we call round(at_present ) to round at_present to the nearest integer, round(at_present , 2) to round at_present to two digits after the decimal, round(at_present , 4) to round at_present to four digits after the decimal.
0 comments:
Post a Comment