Home »
Python »
Python programs
Python program to get current time
Here, in this program, we are going to learn how to get the current time date using Python? This is an example of Python datetime module.
Submitted by IncludeHelp, on March 09, 2020
There are different ways to get the current time in Python,
1) Getting current time using time module
Steps:
- Import the time module
- Call the localtime() function of the time class – assign it in its object.
- Format the time using strftime() function.
# Python program to get current time
# importing the time module
import time
# getting the current time
time_object = time.localtime()
# format the time
current_time = time.strftime("%H:%M:%S", time_object)
# print the time
print("Current time is: ", current_time)
Output
Current time is: 08:04:32
2) Getting current time using datetime object
Steps:
- Import the datetime class from datetime module
- Call the now() function of datetime class
- Pass the object in the strftime() function to format the time
- Print the time
# Python program to get current time
# importing the datetime class
# from datetime module
from datetime import datetime
# calling the now() function
obj_now = datetime.now()
# formatting the time
current_time = obj_now.strftime("%H:%M:%S")
print("Current time is:", current_time)
Output
Current time is: 08:08:53
3) Getting current time of different time zones
Steps:
- Import the datetime class from datetime module
- Importing the pytz module to access date time from a specified time zone
- Using timezone() function of pytz module – we can specify the time zone, using "now()" function – we can access the current time and using strftime() function – we can format the time.
- Print the time
# Python program to get current time
# importing the datetime class from
# datetime module
from datetime import datetime
# importing the pytz
import pytz
# specifying the indian time zoe
tz_IN = pytz.timezone('Asia/Calcutta')
datetime_IN = datetime.now(tz_IN)
print("Asia/Calcutta time is: ", datetime_IN.strftime("%H:%M:%S"))
# specifying the America/Chicago time zone
tz_Chicago = pytz.timezone('America/Chicago')
datetime_Chicago = datetime.now(tz_Chicago)
print("America/Chicago time is: ", datetime_Chicago.strftime("%H:%M:%S"))
Output
Asia/Calcutta time is: 13:55:15
America/Chicago time is: 03:25:15
TOP Interview Coding Problems/Challenges