How to Subtract Dates and Times in Python

The datetime module is important to understand when learning how to work with dates and times in Python. This module provides various functions and classes to deal with dates, times, and time intervals. It also deals with various operations on dates and times such as arithmetic, comparison, etc.

The datetime module can help calculate a difference between two dates, or timedelta objects. You can also subtract other times from your chosen element by using different periods like years/months/hours etc…

import datetime

start_date =, 5, 1)
end_date =, 5, 14)

period = end_date - start_date
print("Period: " + str(period))
#Period: 13 days, 0:00:00

days = str(end_date - start_date).split(',')[0]
print("Days: " + days)
#Days: 13 days
import datetime

billing_date =, 5, 30)
days = datetime.timedelta(100)
print("Order Date: " + str(billing_date - days))
#Order Date: 2022-02-19
import datetime
from dateutil.relativedelta import relativedelta

subscription_date =, 5, 31) - relativedelta(months = 6)

subscription_date =, 5, 31) - relativedelta(years = 2)

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.