Use the datetime method and the operator < and its kin.

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)
Answer from Fred Foo on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ having trouble comparing datetime objects.
r/learnpython on Reddit: Having trouble comparing datetime objects.
June 3, 2020 -

Here is what I have so far but I keep getting an error:

first = datetime.datetime(d1) TypeError: an integer is required (got type datetime.date)

import datetime

def is_before(d1,d2):
    """
    Returns True if event d1 happens before d2.
    """
    first = datetime.datetime(d1)
    second = datetime.datetime(d2)
    
    before = False
    
    if first < second:
        before = True
        
    return before        

Not sure why it won't work this way. I have looked up the documentation for the datetime data types in Python Library and can't figure out how to fix this.

Thank you for all help

๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_datetime.asp
Python Datetime
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ comparing-dates-python
Comparing dates in Python - GeeksforGeeks
July 11, 2025 - from datetime import date, timedelta ... ] dates.sort() for d in dates: print(d) ... We can also use subtraction between date objects and compare the result using timedelta....
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ whatsnew โ€บ 3.14.html
Whatโ€™s new in Python 3.14
February 23, 2026 - Add the strptime() method to the datetime.date and datetime.time classes. (Contributed by Wannes Boeykens in gh-41431.) Add Decimal.from_number() as an alternative constructor for Decimal. (Contributed by Serhiy Storchaka in gh-121798.) Expose IEEEContext() to support creation of contexts corresponding to the IEEE 754 (2008) decimal interchange formats. (Contributed by Sergey B Kirpichev in gh-53032.) Comparison pages with highlighted changes generated by the HtmlDiff class now support โ€˜dark modeโ€™. (Contributed by Jiahao Li in gh-129939.)
๐ŸŒ
InfluxData
influxdata.com โ€บ home โ€บ python date comparison: a comprehensive tutorial
Python Date Comparison: A Comprehensive Tutorial | InfluxData
October 20, 2023 - You can use the date class to compare two dates without considering time. The following example demonstrates this: from datetime import datetime # Create two datetime objects with time datetime1 = datetime(2023, 3, 20, 12, 0, 0) datetime2 = ...
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ comparing date & time in python [easy step by step]
Comparing Date & Time in Python [Easy Step By Step] - AskPython
January 28, 2023 - For this, we shall use an exclusive command in Python known as the timedelta(). Following is its syntax, timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) This command cannot be used right away, rather ...
Find elsewhere
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ python tutorial: how to compare dates in python
Python Tutorial: How to Compare Dates in Python - Pierian Training
April 28, 2023 - We then use the comparison operators to check if `date1` comes before or after `date2`, or if they are the same. Another way to compare dates in Python is by using string formatting.
๐ŸŒ
FastAPI
fastapi.tiangolo.com โ€บ python-types
Python Types Intro - FastAPI
Pydantic is a Python library to perform data validation. You declare the "shape" of the data as classes with attributes. And each attribute has a type. Then you create an instance of that class with some values and it will validate the values, convert them to the appropriate type (if that's the case) and give you an object with all the data. And you get all the editor support with that resulting object. ... from datetime import datetime from pydantic import BaseModel class User(BaseModel): id: int name: str = "John Doe" signup_ts: datetime | None = None friends: list[int] = [] external_data = { "id": "123", "signup_ts": "2017-06-01 12:22", "friends": [1, "2", b"3"], } user = User(**external_data) print(user) # > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] print(user.id) # > 123
๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to compare dates in python
How to Compare Dates in Python
August 6, 2024 - In Python, we can compare datetime objects directly using comparison operators. This is possible because datetime objects have a natural chronological order.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-do-we-compare-python-dates
How do we compare Python Dates?
September 5, 2022 - Here we use the datetime.date() method to compare two dates. We import datetime module to work with date as date objects.
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python datetime โ€บ python compare two dates
Python Compare Two Dates [3 Ways] โ€“ PYnative
October 10, 2022 - Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format. For example, the %Y/%m/%d format codes are for yyyy-mm-dd. ... Use comparison operators (like <, >, <=, >=, !=, etc.) to compare dates in Python.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-find-the-difference-between-two-dates-in-python-397994
How to find the difference between two dates in Python | LabEx
You can use date comparison to: Check if a given date is within a specific date range ... from datetime import date, timedelta ## Check if a date is within a date range today = date.today() start_date = date(2023, 5, 1) end_date = date(2023, 5, 31) if start_date <= today <= end_date: print(f"{today} is within the date range of {start_date} and {end_date}.")...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ library โ€บ datetime.html
datetime โ€” Basic date and time types
The default behavior can be changed by overriding the special comparison methods in subclasses. In Boolean contexts, all date objects are considered to be true. ... Return a new date object with the same values, but with specified parameters updated. ... >>> import datetime as dt >>> d = dt.date(2002, 12, 31) >>> d.replace(day=26) datetime.date(2002, 12, 26)
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-compare-datetime
Python Compare DateTime
Python Compare DateTime - To compare two datetime objects, you can use comparison operators like greater than, less than, equal to or others. Like any other comparison operation, a boolean value is returned.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ comparing-datetimes-in-python-with-and-without-timezones
Comparing Datetimes in Python with and without Timezones
August 25, 2021 - 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.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ user_guide โ€บ 10min.html
10 minutes to pandas โ€” pandas 3.0.1 documentation
In [18]: df2.dtypes Out[18]: A float64 B datetime64[us] C float32 D int32 E category F str dtype: object In [19]: df2.to_numpy() Out[19]: array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'], [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo'], [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'test', 'foo'], [1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'train', 'foo']], dtype=object)
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ index.html
The Python Standard Library โ€” Python 3.14.3 documentation
datetime โ€” Basic date and time types ยท zoneinfo โ€” IANA time zone support ยท calendar โ€” General calendar-related functions ยท collections โ€” Container datatypes ยท collections.abc โ€” Abstract Base Classes for Containers ยท heapq โ€” Heap queue algorithm ยท
๐ŸŒ
Studytonight
studytonight.com โ€บ python-howtos โ€บ how-to-compare-two-dates-in-python
How to Compare two dates in Python - Studytonight
January 20, 2021 - We will use greater than operator > to check if one datetime object is greater than other datetime objects. If we take the current date and time, and some past date and time for comparing the two dates., the current date and time will be greater than that of the past date we have chosen.