How to Find Difference Between Two Dates in Python: Simple Guide
datetime module. Create date or datetime objects and subtract one from the other to get a timedelta object representing the difference.Quick Comparison
Here is a quick comparison of key points when finding date differences in Python:
| Aspect | Using datetime.date | Using datetime.datetime |
|---|---|---|
| Type of objects | date objects (year, month, day) | datetime objects (year, month, day, hour, minute, second) |
| Time included? | No, only date | Yes, includes time of day |
| Difference result | timedelta (days) | timedelta (days, seconds, microseconds) |
| Use case | Simple date difference | Precise difference including time |
| Example subtraction | date2 - date1 | datetime2 - datetime1 |
Key Differences
The datetime.date class represents just the date without any time information. When you subtract two date objects, the result is a timedelta object that tells you the difference in days.
On the other hand, datetime.datetime includes both date and time (hours, minutes, seconds). Subtracting two datetime objects gives a timedelta that includes days, seconds, and microseconds, allowing you to measure differences more precisely.
Choosing between them depends on whether you need to consider time or just the date. Both use subtraction operator - to find the difference, but the detail level of the result varies.
Code Comparison
Here is how to find the difference between two dates using datetime.date:
from datetime import date # Define two dates date1 = date(2024, 4, 20) date2 = date(2024, 5, 1) # Calculate difference diff = date2 - date1 print(f"Difference: {diff.days} days")
datetime.datetime Equivalent
Here is how to find the difference between two date-times using datetime.datetime:
from datetime import datetime # Define two datetime objects dt1 = datetime(2024, 4, 20, 14, 30) dt2 = datetime(2024, 5, 1, 16, 45) # Calculate difference diff = dt2 - dt1 print(f"Difference: {diff.days} days and {diff.seconds // 3600} hours")
When to Use Which
Choose datetime.date when you only care about the difference in whole days between two dates, such as calculating age in days or days until an event.
Choose datetime.datetime when you need to measure the difference including hours, minutes, or seconds, like timing events or calculating durations precisely.
Using the right type keeps your code simple and your results accurate for your needs.