PUBLISHED ON: AUGUST 23, 2021
Python program to get Current Time
In this tutorial, we will perform a program that will give us the current time. The program can be done with two different methods which we will be covering in this tutorial.
The two different approaches are as follows:
-
Using datetime
-
Using time
Let us first get familiar with the input-output.
Approach-1
Approach-2
Let us now dive deep into both the approaches one by one:
Approach 1 - Using datetime
In this approach, we will import datetime and print the current time in the format of "Hour", "Minute", "Second", "Microsecond". Let us now see the algorithm:
Algorithm
- import datetime module
- use now() to get the current time
- Print the hour
- Print the minute
- Print the second
- Print the microsecond
Program
import datetime
time = datetime.datetime.now()
print ("The current time is : ")
print ("Hour : ", end = "")
print (time.hour)
print ("Minute : ", end = "")
print (time.minute)
print ("Second : ", end = "")
print (time.second)
print ("Microsecond : ", end = "")
print (time.microsecond)
The current time is :
Hour: 18
Minute: 36
Second: 8
Microsecond: 334591
Approach 2 - Using time
In this approach, we will import time and print the current time in the format of "HOUR: MINUTE: SECOND" format. Let us now see the algorithm:
Algorithm
- Import time
- Declare t with the local_time()
- Use time. strftime to get the current time
- Print the current time
Program
import time
t = time.localtime()
time = time.strftime("%H:%M:%S", t)
print("The current time is:", time)
The current time is: 18:41:13
Conclusion
In this tutorial, we will perform a program to get the current time with two different approaches. The first approach is by using datetime and the second approach is by using time.