Compare two dates in Python
This post will discuss how to compare two dates in Python.
1. Using datetime comparison
A simple solution is to use the < or > operators on the given datetime objects to determine which one is earlier. The following example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from datetime import datetime if __name__ == '__main__': first = datetime(2020, 1, 1) second = datetime.now() if first < second: print('First date is less than the second date.') elif first > second: print('First date is more than the second date.') else: print('Both dates are the same.') |
You can also find the difference between two datetime objects to get a timedelta object and perform the comparison based on the positive or negative value returned by the timedelta.total_seconds() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from datetime import datetime if __name__ == '__main__': first = datetime(2020, 1, 1) second = datetime.now() seconds = (first - second).total_seconds() if seconds < 0: print('First date is less than the second date.') elif seconds > 0: print('First date is more than the second date.') else: print('Both dates are the same.') |
2. Using time.struct_time comparison
If dates are given in the string format, you can easily convert them to Python’s date format. Then use the < or > operators to perform the comparison:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import time if __name__ == '__main__': x = "01/01/2020" y = "01/31/2020" first = time.strptime(x, "%m/%d/%Y") second = time.strptime(y, "%m/%d/%Y") if first < second: print('First date is less than the second date.') elif first > second: print('First date is more than the second date.') else: print('Both dates are the same.') |
That’s all about comparing two dates in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)