Date and Time

Introduction
Computers handle time using ticks. To get the date or time in Python we need to use the standard time module.

Note: All computers keep track of time since 12:00am, January 1, 1970, known as epoch time.

 
Related Course:

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()))
print(timenow)

This will show output as:

Sat Dec 19 15:44:40 2015

 

Previous Post
Next Post

2 Replies to “Date and Time”

Leave a Reply

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