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 into 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.
The above code simply prints out the full-time up to the accuracy of microseconds, as you can see in the screenshot of the output.
You can format the output in 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)
Using the time package
There is another pre-installed time package to get this job done. Under the time module, you have to import 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.
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.