There are many methods to print current time in Python. It can be done either using the DateTime objector or the Time module in Python. Here we will go through various methods and will print the current time. The current time will contain the date and the time.
Print the Current Time in Python
The print() method in Python is used to display the staff on the console. We will use various methods and examples to display the current date and time in Python.
The two most common ways in Python to get the current date and time are:
- DateTime Object
- Time Module
We will use both methods to find the current time.
Current Time Using DateTime Object
To get the current time, we need to import the datetime module and use the now() method. You don’t need to be worried about the installation of the datetime module because it is a Python built-in module.
Here is how we can print the current time using the datetime object method:
# importing the module
from datetime import datetime
# finding the current time
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
# printing
print("Current Time =", current_time)
Output:
Current Time = 18:42:43
As you can see, we got the exact time along with the seconds. If you want to get the date, you can change the parameters as shown below:
current_time = now.strftime("%D")
# printing
print("Current Time =", current_time)
Output:
Current Time = 07/23/23
The current date was printed.
Current Time Using the Time Module
The Time module in Python also provides a useful method to find the current time and date. Let us take an example and see how it actually works.
# importing the time
import time
# current time
Time = time.localtime()
current_time = time.strftime("%H:%M:%S", Time)
print("Current Time: ",current_time)
Output:
Current Time: 18:57:32
As you can see, we got the current time.
Conclusion
The Time module and the TimeDate objects are the two most common ways to find the current time in Python. In this short article, we learned different methods to print the current time.
Related Articles
- How to Delete a Column in Pandas?
- How to Plot Mean of Dataframe in Pandas?
- Plot Normal Distribution in Python With Examples