Python can get the system time using the module time. TIme is not part of the standard library. You can load this module by typing import time.
The time module has all kinds of time related functions. Not all functions exist on all operating systems.
The time module starts counting from epoch time, which is 1st January 1970.
Practice now: Test your Python skills with interactive challenges
Example
Current time
In the example below we output the day,month and year followed by the current time.
The first line returns all variables required (year,month,day,hour,minute).
timenow = time.localtime(time.time())
The function time.time() returns ticks. Ticks are system ticks every computer holds.
timenow = time.localtime(time.time())
As humans we don't read system ticks, this needs to be converted to actual human time. The function localtime() converts these ticks into the actual human readable values.
year,month,day,hour,minute = timenow[0:5]
Convert with:
timenow = time.localtime(time.time())
Type the program shown below and run it:
import time
timenow = time.localtime(time.time())
year,month,day,hour,minute = timenow[0:5]
print(str(day) + "/" + str(month) + "/" + str(year))
print(str(hour) + ":" + str(minute))
Epoch time
How do you get the number of seconds since epoch time? The time() method will give you that:
>>> import time
>>> time.time()
1563018526.7016013
>>> time.time()
1563018527.5820937
>>>
To get the time sequence call time.gmtime().
>>> time.gmtime()
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=13, tm_hour=11, tm_min=49, tm_sec=39, tm_wday=5, tm_yday=194, tm_isdst=0)
Time in string
The methods asctime() and ctime() return a 24 character string. Without arguments it gets the current time.
>>> time.asctime()
'Sat Jul 13 13:53:00 2019'
>>> time.ctime()
'Sat Jul 13 13:53:01 2019'
>>>
Sleep
You can make the program hault execution. The program won't do anything but wait. The sleep module lets you do that.
import time
print("Hello")
time.sleep(1)
print("World")
time.sleep(1)
Practice now: Test your Python skills with interactive challenges
Practice Exercises
Try the exercises below 1. Print the date in format year-month-day
After completing these continue with the next exercise.