Difference between two dates in Python
Codemia Knowledge Hub ·
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
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.