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.
Related course: Complete Python Programming Course & Exercises
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).1
timenow = time.localtime(time.time())
The function time.time() returns ticks. Ticks are system ticks every computer holds.1
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.1
year,month,day,hour,minute = timenow[0:5]
Convert with:1
timenow = time.localtime(time.time())
Type the program shown below and run it:1
2
3
4
5
6
7import 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:
1 | import time |
To get the time sequence call time.gmtime()
.
1 | time.gmtime() |
Time in string
The methods asctime() and ctime() return a 24 character string. Without arguments it gets the current time.
1 | time.asctime() |
Sleep
You can make the program hault execution. The program won’t do anything but wait. The sleep module lets you do that.
1 | import time |
If you are a beginner, then I highly recommend this book.
Exercise
Try the exercises below
- Print the date in format year-month-day
After completing these continue with the next exercise.