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

Computers keep track of time since 12:00am, January 1, 1970. This is commonly known as epoch time. This is almost always converted to human readable time.

Related Course: Complete Python Programming Course & Exercises

Epoch time

To get the number of ticks (the epoch time), there are several things you need to do.
First import the time module. You don’t need to install this module, as it’s part of the Python core library.

import time 

Then call the method time.time(). This method returns the number of ticks, so store that into a variable.
Then you can output the number of ticks to the screen.

That gives you this program:

import time 

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

The output will be similar to this:

Ticks since epoch: 1450535867.84

This is correct (the epoch time), but it doesn’t tell us me. You can convert this to normal time format using local time.

Local time

You’ve seen before how to get the number of ticks. You can convert ticks to local time using the method time.localtime(ticks).

import time
ticks = time.time()
timeNow = time.localtime(ticks)
print(timeNow)

Or you can write a slighlty more compact version:

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:

python local time

So what to do now?

Formatting

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.

If this looks a bit tricky, let me tell you a little trick: f-strings or formatted strings. This is a feature of Python 3.6 and newer.

s = f"{timeNow.tm_mday}/{timeNow.tm_mon}/{timeNow.tm_year}"
print(s)

It will then output something like:

17/2/2020

If you don’t like to use f-strings, 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

Download exercises