How to compare time in different time zones in Python?

PythonServer Side ProgrammingProgramming

When you have 2 different time objects with different timezones and you need to compare them, you first need to understand the difference between aware and naive objects. An aware datetime object is an object that holds the information about the timezone while naive object doesn't hold any timezone information.

The easiest way to compare 2 aware objects to check whether they tell the same time or not is to directly compare them.

Example

import datetime, pytz
local_tz = pytz.timezone('CET')
# Get the time in UTC
utc = datetime.datetime.now(pytz.utc)
# Convert the time to local timezone
local = utc.astimezone(local_tz)
print("UTC: ", utc)
print("Local: ", local)
print(utc == local)

Output

This will give the output −

UTC:  2018-01-03 17:02:43.632805+00:00
Local:  2018-01-03 18:02:43.632805+01:00
True
raja
Published on 08-Jan-2018 15:02:10
Advertisements