Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I calculate number of days between two dates using Python?
In this article we will discuss how to find the number of days between two dates using Python. We use the datetime module to calculate the difference between dates, which returns a timedelta object containing the number of days.
Using datetime.date()
Python's built-in datetime module provides the date class for handling dates. To find the difference between two dates, we create date objects and subtract them ?
Syntax
datetime.date(year, month, day)
Parameters
- year − Integer representing the year (MINYEAR ? year ? MAXYEAR)
- month − Integer representing the month (1 ? month ? 12)
- day − Integer representing the day (1 ? day ? days in given month and year)
Return Value
Returns a date object with the specified year, month and day. When two date objects are subtracted, it returns a timedelta object containing the difference.
Example
Here's how to calculate the number of days between two dates ?
from datetime import date
d0 = date(2011, 1, 8)
d1 = date(2015, 8, 16)
delta = d1 - d0
print('The number of days between the given range of dates is:')
print(delta.days)
The number of days between the given range of dates is: 1681
Using datetime.datetime()
For more precise calculations including time, you can use datetime objects ?
from datetime import datetime
start_date = datetime(2023, 1, 15, 10, 30, 0)
end_date = datetime(2023, 2, 20, 14, 45, 0)
difference = end_date - start_date
print(f"Days: {difference.days}")
print(f"Total seconds: {difference.total_seconds()}")
Days: 36 Total seconds: 3135300.0
Using String Dates with strptime()
When working with date strings, parse them first using strptime() ?
from datetime import datetime
date_str1 = "2023-05-15"
date_str2 = "2023-07-22"
date1 = datetime.strptime(date_str1, "%Y-%m-%d")
date2 = datetime.strptime(date_str2, "%Y-%m-%d")
days_diff = (date2 - date1).days
print(f"Number of days: {days_diff}")
Number of days: 68
Comparison of Methods
| Method | Use Case | Precision |
|---|---|---|
date() |
Date-only calculations | Days only |
datetime() |
Date and time calculations | Microseconds |
strptime() |
String date parsing | Based on format |
Conclusion
Use datetime.date() for simple day calculations and datetime.datetime() when you need time precision. The timedelta object provides easy access to the difference in days through its .days attribute.
