Порівняння двох дат

Python:
Порівняння двох дат

How to: (Як це зробити:)

Here’s a simple way to compare dates using Python:

from datetime import datetime

# First date in YYYY-MM-DD format
date_string_1 = "2023-04-01"
# Second date in the same format
date_string_2 = "2023-08-24"

# Convert strings to datetime objects
date_1 = datetime.fromisoformat(date_string_1)
date_2 = datetime.fromisoformat(date_string_2)

# Compare the two dates
if date_1 < date_2:
    print(f"{date_string_1} comes before {date_string_2}")
elif date_1 > date_2:
    print(f"{date_string_1} comes after {date_string_2}")
else:
    print(f"{date_string_1} is the same as {date_string_2}")

Sample output for the above code:

2023-04-01 comes before 2023-08-24

Deep Dive (Поглиблений аналіз):

Long before Python, people compared dates using calendars and calculations. In Python, the datetime module became the go-to way to manage dates and times post its introduction in version 2.3.

There are alternatives like using timestamps or third-party libraries (like dateutil). Still, datetime is robust and built-in, meaning fewer dependencies.

Under the hood, datetime objects are compared based on their internal representation of date and time, which makes these operations reliable and fast.

See Also (Дивіться також):