Comparing Datetimes in Python – With and Without Timezones

python_tutorials

Introduction

When working with dates, oftentimes, you’d like to know if a given date comes before or after another date. We can get these answers by comparing dates.

In this article, we will learn how to use the Python datetime module to create and compare both naive (without timezone info) and aware (with timezone info) dates.

To compare the dates, we will use the comparison operators in Python: <, >, ==, <=, >=, !=.

Note: The datetime module has two methods for creating dates object – datetime.datetime and datetime.date. Comparisons can only be made on objects created from the same class:

datetime.datetime.now() >= datetime.date.today()

This will result in a TypeError:

TypeError: can't compare datetime.datetime to datetime.date

Comparing Timezone-Naive Datetimes

Let’s start off with comparing naive dates, which don’t have any timezone information. First, we’ll want to import the datetime module:

from datetime

 

 

To finish reading, please visit source site