Difference between two dates in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To calculate the difference between two dates in Python, subtract one datetime.date or datetime.datetime object from another. The result is a timedelta object that stores the difference in days, seconds, and microseconds. Access the total difference in days with .days or in seconds with .total_seconds(). For more human-readable differences (years, months), use the dateutil.relativedelta module. The built-in datetime module handles most use cases without external dependencies.
Basic Date Difference
Subtracting two date objects returns a timedelta. The .days attribute gives the difference as an integer number of days.
DateTime Difference (With Time)
For datetime objects, the timedelta includes both days and time components. Use .total_seconds() to get the complete difference as a single number, including the days portion.
Parsing Date Strings
strptime converts a date string to a datetime object using format codes (%Y = year, %m = month, %d = day, %H = hour, %M = minute, %S = second).
Difference in Years and Months (dateutil)
The built-in timedelta only stores days and seconds — it cannot express differences in months or years (because months have variable lengths). dateutil.relativedelta handles calendar-aware differences.
Working with Timezones
When both datetimes are timezone-aware, subtraction correctly accounts for the UTC offset. Mixing timezone-aware and naive datetimes raises TypeError.
Business Days Difference
Common Date Calculations
Formatting the Difference
Common Pitfalls
- Using
.secondsinstead of.total_seconds():timedelta.secondsonly returns the seconds component (0-86399), ignoring the days. For a 3-day difference,.secondsis0while.total_seconds()is259200. Always use.total_seconds()for the complete difference. - Mixing timezone-aware and naive datetimes: Subtracting a timezone-aware datetime from a naive one raises
TypeError: can't subtract offset-naive and offset-aware datetimes. Either make both aware or both naive before comparing. - Assuming months have fixed length:
timedeltadoes not support months because months have 28-31 days.timedelta(months=1)is not valid. Usedateutil.relativedelta(months=1)for calendar-aware month arithmetic. - Negative timedelta confusion:
date(2025, 1, 1) - date(2025, 3, 1)returns a negativetimedeltawith.days = -59. Useabs()to get the absolute difference regardless of order. - Forgetting
strptimeformat mismatches:datetime.strptime("15/01/2025", "%Y-%m-%d")raisesValueErrorbecause the format does not match the string. The format string must exactly match the input pattern.
Summary
- Subtract two
dateordatetimeobjects to get atimedeltawith the difference - Use
.daysfor whole days and.total_seconds()for the complete difference in seconds - Use
dateutil.relativedeltafor differences in years, months, and days - Parse date strings with
datetime.strptime()before performing arithmetic - Use
abs()to get a positive difference regardless of date order - Make both datetimes timezone-aware or both naive to avoid
TypeError
Related reading
- difference between variables inside and outside of __init__ class and instance attributes
- Difference in Boto3 between resource, client, and session?
- Differences between distribute, distutils, setuptools and distutils2?
- Different result with roc_auc_score and auc
- Dijkstra's algorithm in python
- Directory-tree listing in Python
- Disable boto logging without modifying the boto files
- Disable individual Python unit tests temporarily
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.