How to get current time in Python
There are several ways to get the current time in Python. This tutorial will show you various simple methods that are available in Python to do this. The following are the topics that we are going to see with examples.
Example 1: Get current time in Python
from datetime import datetime Time = datetime.now() Current_Time = Time.strftime("%H:%M:%S") print("Current Time:",Current_Time)
In the above example, we have used the datetime class which is imported from the datetime module. We have used the now() function to create a datetime object which contains date and time. The strftime() function returns a string representing time as specified by format argument. If we run the above program the output will be as follows. The output will show the result in HH:MM:SS format.
Current Time: 13:54:12
Example 2: Get current date with time
This example will show you how to get the current date with time using a simple program.
from datetime import datetime Cu_DateTime = datetime.now() print (Cu_DateTime.strftime("%Y-%m-%d %H:%M:%S"))
In this example also, we have imported the datetime class from the datetime module. In python, now() function returns the current local date and time in YYYY-MM-DD HH:MM:SS format which is defined in the datetime module. We can get the current date and time simultaneously in Python by simply adding a date format specifier along with time format specifier in strftime() function.