How To Get Current Time In Python?

Get Current Time In Python

This is a quick tutorial on how to get the current time in python. The most common and simplest ways to get time in python are discussed here with examples.

Using the datetime package

Python comes with a pre-installed datetime package. All you need to do is to import this package in your python program and then you can easily use the current time as you wanted. The example code is given below.

from datetime import datetime
time = datetime.now()
print(time)

Output.

Python Get Current Time With DateTime Module

The above code simply prints out the full time upto the accuracy of microseconds, as you can see in the screenshot of the output.

You can format the output as the way you like by using this module as illustrated in the following code.

from datetime import datetime
time = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
print(time)

Get Current Time Python Formatted

Using the time package

There another pre-installed time package to get this job done. Under the time module, you have to import the two things, gmtime to get the current time and strftime which will help you to present the current time in the required format.

The strftime function takes two arguments, in the first argument, you’ve to specify the output time format with different symbols for the different units of time. Get the detailed symbol reference here. An example code is illustrated below with output.

from time import gmtime, strftime
time = strftime("%d-%m-%Y %H:%M:%S", gmtime())
print(time)

Output.

Python Get Current Time

Get Current Unix Time Stamp In Python

You can use the time module to get the current Unix timestamp as well. Just run the following code.

import time
time = time.time()
print(time)

Output.

Python Get Current Unix Timestamp

Related Articles.

Leave a Reply

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