Python:
日付を比較する

How to: (方法)

from datetime import datetime

# Create two date objects
date1 = datetime(2023, 3, 14)
date2 = datetime(2023, 4, 18)

# Compare the dates
print("Is date1 before date2?", date1 < date2)  # True
print("Is date1 after date2?", date1 > date2)   # False
print("Are both dates the same?", date1 == date2)  # False

Sample output:

Is date1 before date2? True
Is date1 after date2? False
Are both dates the same? False

Deep Dive (深掘り)

Python’s built-in datetime module has been around since version 2.3. It provides objects for date and time handling. Before datetime, programmers used time tuples or third-party libraries. As alternatives, the dateutil library offers powerful extensions. When comparing, Python internally converts dates to their integer timestamp representation, simplifying comparison.

See Also (関連情報)