Python: Compare Date or Datetime With and Without Timezones

In this tutorial, we will introduce how to compare python date or datetime for python beginners.

Python: Compare Date or Datetime With and Without Timezones


We can not compare date and datetime object in python, otherwise, we will get an error:

For example: >=

Run this code, you will get an error:

TypeError: can't compare datetime.datetime to

2.Compare date

Look at this example:

from datetime import datetime, date

date1 = date(1995, 3, 20)
date2 = date(2020, 1, 1)

Here date1 and date2 are date objects.

print("date1 comes before date2?", date1 < date2)
print("date1 comes after date2?", date1 > date2)
print("date1 is equal to date2?", date1 == date2)

Run this code, you will get the compared result.

date1 comes before date2? True
date1 comes after date2? False
date1 is equal to date2? False

3.Compare datetime

dob_a = datetime(1995, 3, 20)
dob_b = datetime(2020, 1, 1)

Here dob_a and dob_b are datetime objects.

We can compare them as follows:

if  dob_a > dob_b:
    print("person a is older than person b")
    print("person b is older than person a")

Run this code, you will see:

person b is older than person a

4.Compare date and datetime with timezone

We should localize the given date according to the timezone objects. Here is an example:

from datetime import datetime
import pytz

# Create timezone objects for different parts of the world
tz_ny= pytz.timezone('America/New_York')
tz_lon = pytz.timezone("Europe/London")

# Year, Month, Day, Hour, Minute, Second
datetime = datetime(2010, 4, 20, 23, 30, 0)

# Localize the given date, according to the timezone objects
date_with_timezone_1 = tz_ny.localize(datetime)
date_with_timezone_2 = tz_lon.localize(datetime)

In this example code, we use pytz.timezone() to create two timezones and use .localize() function to localize a given datetime. Then, we can compare them.

# These are now, effectively no longer the same *date* after being localized
print(date_with_timezone_1) # 2010-04-20 23:30:00-04:00
print(date_with_timezone_2) # 2010-04-20 23:30:00+01:00

print(date_with_timezone_1 == date_with_timezone_2)