Date and Time

Online Courses

Computers handle time using ticks. All computers keep track of time since 12:00am, January 1, 1970, known as epoch time. To get the date or time in Python we need to use the standard time module.

Epoch time
To get the number of ticks, use this program:

import time 

ticks = time.time()
print("Ticks since epoch:", ticks)

The output will be similar to this:

Ticks since epoch: 1450535867.84

Local time
To get the current time on the machine, you can use the function localtime:

import time

timenow = time.localtime(time.time())
print("Current time :", timenow)

The output will not be formatted:

Current time : time.struct_time(tm_year=2015, tm_mon=12, tm_mday=19, tm_hour=15, tm_min=42, tm_sec=0, tm_wday=5, tm_yday=353, tm_isdst=0)

You can access each of the elements of the array:

import time

timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])

and use a combination for your own formatting.  One alternative is to use the asctime function:

import time

timenow = time.asctime(time.localtime(time.time()))

This will show output as:

Sat Dec 19 15:44:40 2015



2 thoughts on “Date and Time

  1. Reply
    Huy Nguyen - May 3, 2016

    On your example, the print function is missing the parentheses.

    1. Reply
      admin - May 7, 2016

      Thanks, fixed!

Leave a Reply

Your email address will not be published. Required fields are marked *