Get Current time for Different Time Zone

By | August 18, 2019

Here in this tutorial, we will discuss how can we get the current time of different timezones using python.

Before getting local time for different timezones let’s have a look at how can we get only time using datetime module:

Get the current time using the strftime method:

from datetime import datetime
today = datetime.today()
time = today.strftime("%H:%M")
print("Its =", time)

Output:

Its = 23:02

Behind the code:

In the above example, we have used the strftime() method to extract only hour and minute from the today datetime object.

The problem with the above code is the time is a string which means we would not be able to perform the different datetime operations on it like if we want the difference between two time period we would do it with the help of string time for that we need datetime.time object.

Get current time using datetime object.

Datetime has a special method now().time() which can return the current time

Example:

from datetime import datetime
time = datetime.now().time()
print("Time is =", time)

Output:

Time is = 23:16:45.231031

Behind the code:

In the above example, we have used the datetime now().time() method and assigned it to a variable time. Here the time is a datetime. time object which means we can perform different datetime operations on it.

Local time of different time zones:

Python has a third-party module pytz which is used to get the local time of different timezones.

pytz is not a python standard module so you have to download it using the pip command.

Example:

from datetime import datetime
import pytz
New_York = pytz.timezone('America/New_York')
New_York_date_time = datetime.now(New_York)
print("New York time is:", New_York_date_time.strftime("%H:%M:%S"))
London = pytz.timezone('Europe/London')
London_date_and_Time = datetime.now(London)
print("London time is :", London_date_and_Time.strftime("%H:%M:%S"))

Output:

New York time is: 13:59:58
London time is : 18:59:58

Python Tutorials


Introduction

Flow Control

Functions

Datatypes

File Handling

Object & Class

Additional Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *