Signup/Sign In

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:

  1. Using datetime

  2. Using time

Let us first get familiar with the input-output.

Approach-1

I/O-1

Approach-2

I/0-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

  1. import datetime module
  2. use now() to get the current time
  3. Print the hour
  4. Print the minute
  5. Print the second
  6. 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

  1. Import time
  2. Declare t with the local_time()
  3. Use time. strftime to get the current time
  4. 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.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.