Python can get the system time using the module time.
To use this module type:

import time.

Time is not part of the standard library.

Example

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))

Exercise

Try the exercises below

  1. Print the date in format year-month-day

After completing these continue with the next exercise.

Download answers