[Python] Comparing Dates and Times: Determining Order with Operators

In Python, datetime and date objects can be compared just like numbers using standard comparison operators (<, >, ==, !=).

This allows you to determine which date is newer (future) or if they are the same. The basic rule is: “Future dates are larger” and “Past dates are smaller.”

目次

Implementation Example: Checking Sale Periods

In this example, we will create a program that gets the current date and time and determines whether it has passed a specific “sale end date.”

Source Code

from datetime import datetime

# 1. Set the comparison target (Sale End Date)
# December 31, 2025, 23:59:59
sale_end_date = datetime(2025, 12, 31, 23, 59, 59)

# 2. Get the current date and time
current_date = datetime.now()

print(f"Current Date: {current_date}")
print(f"End Date    : {sale_end_date}")
print("-" * 30)

# 3. Compare dates
# Future (Larger) > Past (Smaller)
if current_date < sale_end_date:
    # Current < End: Still within the period
    print("Result: The sale is currently active!")

elif current_date > sale_end_date:
    # Current > End: The period has passed
    print("Result: Unfortunately, the sale has ended.")

else:
    # Exact match (Rare, but checkable with ==)
    print("Result: It is exactly the end time right now.")

Execution Result

Current Date: 2025-12-19 20:30:15.123456
End Date    : 2025-12-31 23:59:59
------------------------------
Result: The sale is currently active!

(Note: The result depends on the current date and time of execution.)

Explanation

Visualizing Comparison Operators

  • A < B: A is before (past) B.
  • A > B: A is after (future) B.
  • A == B: A and B are the exact same time.

Important Note: Timezone Consistency

When comparing two datetime objects, both must be either “timezone-naive” (no timezone info) or “timezone-aware” (with timezone info).

Comparing a naive object with an aware object will raise a TypeError. (Typically, objects created with datetime.now() and datetime(...) are both naive by default, so they can be compared directly.)

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次