/  Technology   /  How to get the current time in Python

How to get the current time in Python

 

In this article let’s learn different ways to get the current time in Python.

  • Using pytz module
  • Using datetime module
  • Using time module

 

Using pytz module:

Pytz adds the Olson tz database into Python which supports almost all time zones and also has the date-time conversion functionalities. This module helps a user who’s serving an international client’s base. The now() method is used to get an object containing the current date & time. Using this method we are getting the current time in a specified timezone.

Example:

from datetime import *
import pytz

Indian_timezone = pytz.timezone('Asia/Kolkata')
Indian_datetime = datetime.now(Indian_timezone)
print("Time in Asia/Kolkata Timezone:", Indian_datetime.strftime("%H:%M:%S"))

Output:

 

Using datetime module:

The datetime module comes inbuilt in Python and there’s no need of installing it externally. We use the datetime.now() function of the datetime module to get both current date and time. This function returns the current local date and time. 

The strftime() method is used to create a string which represents the current time.

Example:

from datetime import datetime

now_method = datetime,now()

current_time = now_method.strftime("%H:%M:%S")
print("Current Time :", current_time)

Output:

 

Using time module:

To deal with all the time related functions in our Python application we use the time module. The time() function returns the number of seconds passed since epoch. Epoch is the point where time begins. For the Unix system, January 1, 1970, 00:00:00 at UTC is epoch.

Example:

import time

Time = time.localtime()

current_time = time.strftime("%H:%M:%S", Time)
print(current_time)

Output:

 

Leave a comment