Python compare two datetime

Comparing Datetimes in Python

In Python, we can easily compare two datetimes to see which datetime is later than another with >, and == operators just like when comparing numbers.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1 < datetime2) print(datetime1 >datetime2) print(datetime1 == datetime2) #Output: True False False

You can also use these same operators to compare two dates in Python.

import datetime datetime1 = datetime.date(2022,3,5) datetime2 = datetime.date(2022,3,8) print(datetime1 < datetime2) print(datetime1 >datetime2) print(datetime1 == datetime2) #Output: True False False

When working in Python, many times we need to create variables which represent dates and times. Being able to easily determine which dates or datetime variables are later or before other variables is very valuable.

We can easily compare datetimes in Python using the standard comparison operators >, and ==.

Below is a simple example of comparing two datetimes in Python.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1 < datetime2) print(datetime1 >datetime2) print(datetime1 == datetime2) #Output: True False False

You can also use these same operators to compare two dates in Python.

import datetime datetime1 = datetime.date(2022,3,5) datetime2 = datetime.date(2022,3,8) print(datetime1 < datetime2) print(datetime1 >datetime2) print(datetime1 == datetime2) #Output: True False False

How to Check if a datetime is Later Than Another datetime in Python

To check if a datetime is later than another datetime, use the > operator.

Читайте также:  Что означает stylesheet css

Below is a simple example in Python of how to compare datetimes to see which datetime is later than the other.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1 > datetime2) #Output: False

How to Check if a datetime is Earlier Than Another datetime in Python

To check if a datetime is earlier than another datetime, use the operator.

Below is a simple example in Python of how to compare datetimes to see which datetime is earlier than the other.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1 < datetime2) #Output: True

How to Check if a datetime is Equal to Another datetime in Python

To check if a datetime is equal to another datetime, use the == operator.

Below is a simple example in Python of how to compare datetimes to see which datetime is equal to another.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1 == datetime2) #Output: False

Comparing Dates of Two datetime Objects in Python

If you just want to compare the dates of datetime objects in Python, we can easily do that by calling the date() function.

The date() function removes the time from the datetime. Then, you can use the comparison operators.

Below is an example of comparing just the dates of two datetimes in Python.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1.date() < datetime2.date()) print(datetime1.date() >datetime2.date()) print(datetime1.date() == datetime2.date()) #Output: True False False

Comparing Times of Two datetime Objects in Python

If you just want to compare the times of datetime objects in Python, we can easily do that by calling the time() function.

The time() function removes the date from the datetime. Then, you can use the comparison operators.

Below is an example of comparing just the times of two datetimes in Python.

import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1.time() < datetime2.time()) print(datetime1.time() >datetime2.time()) print(datetime1.time() == datetime2.time()) #Output: True False False

Hopefully this article has been useful for you to learn how to compare datetimes in Python.

  • 1. Python if else do nothing – Using pass Statement to Do Nothing in Python
  • 2. Python Get Number of Cores Using os cpu_count() Function
  • 3. Using Python to Create Empty DataFrame with pandas
  • 4. How Clear a Set and Remove All Items in Python
  • 5. Convert String to Datetime in pandas with pd.to_datetime()
  • 6. Create Unique List from List in Python
  • 7. Find Last Occurrence in String of Character or Substring in Python
  • 8. Using Python to Calculate Average of List of Numbers
  • 9. How to Remove NaN from List in Python
  • 10. Multiple Condition While Loops in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Python Compare Two Dates

In this lesson, you’ll learn how to compare two dates or datetime in Python.

You’ll learn how to:

  • Check if a given date is greater or less than another date.
  • Compare two timestamps
  • Compare two date string

Table of contents

How to Compare Two Dates in Python

Use comparison operators (like , =, !=, etc.) to compare dates in Python. Let’s see the steps to compare dates with the help of the datetime module.

  1. import datetime modulePython datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.
  2. Convert date string to a datetime object If dates are in a string format, we need to convert both date strings to a datetime object before comparing them.
    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 .
  3. Compare two datetime objects Use comparison operators (like < , >, = , != , etc.) to compare dates in Python. For example, datetime_1 > datetime_2 to check if a datetime_1 is greater than datetime_2.
  4. Compare two dates If you want to compare only the dates of the DateTime object, use the date() method to extract only the date part from the datetime object.
  5. Compare two time To compare only the time of the DateTime object, use the time() method to extract only the time part from the datetime object.

Example 1: Compare Two DateTime

In this example, we’ll check:

  • If the datetime_1 is greater than another datetime.
  • If the datetime_1 is lower than datetime_2.
from datetime import datetime def compare_dates(date1, date2): print('Date1:', date1) print('Date2:', date2) if date1 > date2: print('Date1 is greater than date2') else: print('Date1 is lower than date2') dt1 = datetime(2022, 9, 13) # today's datetime today = datetime.now() compare_dates(dt1, today) dt1 = datetime(2022, 9, 13) dt2 = datetime(2021, 11, 23) compare_dates(dt1, dt2)
Date1: 2022-09-13 00:00:00 Date2: 2022-10-07 15:12:52.970943 Date1 is lower than date2 Date1: 2022-09-13 00:00:00 Date2: 2021-11-23 00:00:00 Date1 is greater than date2

Example 2: Compare Two Dates

Let’s assume you have two datetime objects. One only has the date, and the other one has the date & time parts, and you want to compare the dates only (and not the time).

Now, If you want to compare only the dates of DateTime objects, just use the date() method to extract only the date part from the datetime object.

from datetime import datetime # input dates d1 = datetime(2022, 6, 27).date() d2 = datetime(2022, 6, 27).date() d3 = datetime(2021, 5, 14).date() d4 = datetime(2022, 10, 10).date() # omit .date() function if you want to compare the entire datetime object # use .date() id you want to compare only the date part of it # date equality check print('Date_1:', d1, 'Date_2:', d2, 'Date3:', d3) print('Date_1 and Date_2 are equal:', d1 == d2) print('Date_1 and Date_3 are equal:', d1 == d3) # check if date is greater than another date print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4) print('date_1 is greater than date_3:', d1 > d3) print('date_1 is greater than date_4:', d1 > d4) # check if date is less than another date print('Date_1:', d1, 'Date_3:', d3, 'Date_4:', d4) print('date_1 is less than date_3:', d1 < d3) print('date_1 is less than date_4:', d1 < d4) # date not equal to check print('Date_1:', d1, 'Date_2:', d2, 'Date__3:', d3) print('Date_1 and Date_2 are NOT equal:', d1 != d2) print('Date_1 and Date_3 are NOT equal:', d1 != d3)
Date_1: 2022-06-27 Date_2: 2022-06-27 Date3: 2021-05-14 Date_1 and Date_2 are equal: True Date_1 and Date_3 are equal: False Date_1: 2022-06-27 Date_3: 2021-05-14 Date_4: 2022-10-10 date_1 is greater than date_3: True date_1 is greater than date_4: False Date_1: 2022-06-27 Date_3: 2021-05-14 Date_4: 2022-10-10 date_1 is less than date_3: False date_1 is less than date_4: True Date_1: 2022-06-27 Date_2: 2022-06-27 Date__3: 2021-05-14 Date_1 and Date_2 are NOT equal: False Date_1 and Date_3 are NOT equal: True

Example 3: Compare Times of two DateTime Objects

Let’s assume you have two datetime objects. One only has the time, and the other one has the date & time parts, and you want to compare the times only (and not the date).

Use the time() method to extract only the time part from the datetime object.

from datetime import datetime # date in yyyy/-mm-dd hh:mm:ss format dt_1 = datetime(2022, 6, 27, 18, 45, 53) dt_2 = datetime(2022, 6, 27, 21, 12, 34) # use .time() if you want to compare only the time part of it # date equality check print('Time_1:', dt_1.time(), 'Time_2:', dt_2.time()) print('Both times are equal:', dt_1.time() == dt_2.time()) print('Times not equal:', dt_1.time() != dt_2.time()) print('Time_1 is greater than Time_2:', dt_1.time() > dt_2.time()) print('Time_1 is less than Time_2:', dt_1.time() < dt_2.time())
Time_1: 18:45:53 Time_2: 21:12:34 Both times are equal: False Times not equal: True Time_1 is greater than Time_2: False Time_1 is less than Time_2: True

Compare Two Date String

There may be a case in which dates are in a string format. Before comparing them, we need to convert both date strings to a datetime object.

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . The format codes are standard directives for mentioning the string format for parsing. For example, the %Y/%m/%d format codes are for yyyy-mm-dd .

from datetime import datetime def compare_dates(date1, date2): # convert string to date dt_obj1 = datetime.strptime(date1, "%Y-%m-%d %H:%M:%S") dt_obj2 = datetime.strptime(date2, "%Y-%m-%d %H:%M:%S") print('Date1:', dt_obj1) print('Date2:', dt_obj2) if dt_obj1 == dt_obj2: print('Both dates are equal') elif dt_obj1 > dt_obj2: print('Date1 is greater than date2') else: print('Date1 is lower than date2') # datetime in yyyy-mm-dd hh:mm:ss format dt_str1 = '2022-10-29 8:32:49' dt_str2 = '2022-5-7 4:14:58' compare_dates(dt1_str1, dt2_str2)
Date1: 2022-10-29 08:32:49 Date2: 2022-05-07 04:14:58 Date1 is greater than date2

Compare Two Timestamps in Python

A timestamp is encoded information generally used in UNIX, which indicates the date and time at which a particular event has occurred. This information could be accurate to the microseconds. It is a POSIX timestamp corresponding to the datetime instance.

To compare Python timestamp objects, we can use the same conditional operator we used to compare dates.

from datetime import datetime # input timestamp ts1 = datetime(2022, 6, 27, 18, 45, 32).timestamp() # get current timestamp ts2 = datetime.now().timestamp() print('Timestamp_1:', ts1, 'Timestamp_2:', ts2) # timestamp equality check print('Timestamp_1 and Timestamp_2 are equal:', ts1 == ts2) # check if timestamp_1 is greater than another timestamp print('Timestamp_2 is greater than Timestamp_1:', ts2 > ts1) # check if timestamp_1 is less than another timestamp print('Timestamp_1 is less than Timestamp_2:', ts1 < ts2) # timestamp not equal to check print('Timestamp_1 is NOT equal to Timestamp_2:', ts1 != ts2)
Timestamp_1: 1656335732.0 Timestamp_2: 1665393979.484924 Timestamp_1 and Timestamp_2 are equal: False Timestamp_2 is greater than Timestamp_1: True Timestamp_1 is less than Timestamp_2: True Timestamp_1 is NOT equal to Timestamp_2: True

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью