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 = datetime.date(2022, 5, 1) end_date = datetime.date(2022, 5, 14) period = end_date - start_date print("Period: " + str(period)) #Period: 13 days, 0:00:00 days = str(end_date - start_date).split(',') print("Days: " + days) #Days: 13 days
import datetime billing_date = datetime.date(2022, 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 = datetime.date(2022, 5, 31) - relativedelta(months = 6) print(subscription_date) #2021-11-30 subscription_date = datetime.date(2022, 5, 31) - relativedelta(years = 2) print(subscription_date) #2020-05-31