Calculating Date Differences with Built-in Functions
The datetime
module in Python provides several built-in functions and methods to calculate date differences. These functions make it easy to perform date-related calculations and comparisons.
Calculating the Difference Between Dates
The timedelta
class is used to represent a time difference between two dates or times. You can use the timedelta
object to calculate the number of days, hours, minutes, and seconds between two dates.
from datetime import datetime, date
## Calculate the difference between two dates
start_date = date(2023, 5, 1)
end_date = date(2023, 5, 15)
difference = end_date - start_date
print(difference.days) ## Output: 14
Comparing Dates
You can use the comparison operators (<
, >
, <=
, >=
, ==
, !=
) to compare date
, time
, and datetime
objects.
from datetime import datetime, date
## Compare dates
today = date(2023, 5, 1)
tomorrow = date(2023, 5, 2)
if today < tomorrow:
print("Today is before tomorrow.")
else:
print("Today is on or after tomorrow.")
The datetime
and date
objects have built-in methods to format the date and time information in various ways.
from datetime import datetime
## Format a datetime object
now = datetime(2023, 5, 1, 12, 30, 0)
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) ## Output: 2023-05-01 12:30:00
By understanding these built-in functions and methods, you can easily perform date-related calculations and manipulations in your Python applications.