Python
In this tutorial we will learn about time module in Python.
We learned about modules in the Python - Modules tutorial. Feel free to check that out.
In one of the previous tutorial Python - datetime Module we learned how to work with date and time using the datetime module.
datetime
time
To work with time we have to first import the time module by writing the following line.
import time
To display the current time using the time module we have to write the following code.
# import the module import time # get time currTime = time.time() # output print(currTime)
The above Python code will give us a similar output.
1540080000.431106
The value we get is a floating-point number in seconds.
The time.time() returns the current time in seconds since the Epoch.
time.time()
Epoch = 1st Jan 1970 12:00 am
localtime
We can convert the current time from seconds to time tuple using the localtime method.
In the following Python program we are converting the current time into time tuple.
# import the module import time # get time currTime = time.time() # local time tuple lt = time.localtime(currTime) # output print(lt)
The above code will give us the following output.
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=21, tm_hour=7, tm_min=18, tm_sec=48, tm_wday=6, tm_yday=294, tm_isdst=0)
The output is in struct_time structure and the attributes are in the following format.
asctime
We use the asctime method to coverter the time from seconds to human readable form.
This method takes a time-tuple and returns a human readable 24-character string like Sun Oct 21 07:35:33 2018.
Sun Oct 21 07:35:33 2018
In the following Python program we are converting the current time into human readable form.
# import the module import time # get time currTime = time.time() # local time tuple to human readable form lt = time.asctime(time.localtime(currTime)) # output print(lt)
The above code will give us a similar output.
gmtime
We use the gmtime method to get a time-tuple containing UTC time. This method takes time in seconds.
In the following Python program we are getting the UTC time using the gmtime method.
# import the module import time # get time currTime = time.time() # local time tuple l = time.gmtime(currTime) # output print(l)
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=21, tm_hour=10, tm_min=2, tm_sec=48, tm_wday=4, tm_yday=294, tm_isdst=0)
When using gmtime method we will always get tm_isdst=0.
tm_isdst=0