Sling Academy
Home/Python/How to Compare 2 Dates in Python

How to Compare 2 Dates in Python

Last updated: January 16, 2023

There might be cases where you have to compare 2 dates to determine which one is earlier and which one is later. In Python, you can compare 2 date objects just like comparing 2 numbers by using comparison operators <, >, <=, >=, !=, ==. Let’s say we are given 2 date objects: date1 and date2, then we can compare them like so:

import datetime

date1 = datetime.datetime(2023, 1, 1)
date2 = datetime.datetime(2024, 12, 30)

if(date1 < date2):
    print('date1 is earlier than date2')
elif(date1 > date2):
    print('date2 is earlier than date1')
else:
    print('date1 and date2 are the same')

The output should be:

date1 is earlier than date2

Python also allows you to subtract 2 date objects directly as if they were 2 numbers. The result will be a positive duration, a negative duration, or 0:00:00 (if the 2 dates are equal). Let’s see the example below for more clarity:

import datetime

date1 = datetime.date(2023, 1, 1)
date2 = datetime.date(2024, 1, 2)

print(date1 - date2)
print(date2 - date1)

date3 = datetime.datetime(2025, 1, 3, 10, 30, 45)
date4 = datetime.datetime(2025, 1, 3, 10, 30, 45)
print(date3 - date4)

Output:

-366 days, 0:00:00
366 days, 0:00:00
0:00:00

If you’ve worked with other programming languages before, you’ll probably be a little surprised because the datetime handling in Python is much more simple and convenient.

Next Article: How to Format Date and Time in Python

Series: Date and Time in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots