Today we will learn how to quickly add different time periods to date objects using the Python programming language.
Add days to a date object in Python
In this first example, we will assume that we would like to calculate the expected start date of a new hire in our fictitious company.
Let us start by importing the datetime module into our Python environment and defining two variables: a date and a timedelta.
import datetime # define a datetime sign_date = datetime.date(2022,6, 7) #define a timedelta representing the employee notice notice_interval = datetime.timedelta(days = 60)
Now we’ll go ahead and sum those together, note the usage of the str function that casts the date object so that we can concatenate it into the print statement:
expected_start = sign_date+notice_interval print('The expected start day of this employee is: ' + str(expected_start))
We’ll get the following result:
The expected start of this employee is: 2022-08-06
Add months to date in Python
What if we would like to sum months to a specific date? The timedelta method, supports calculation of time differences up to week granularity. Hence, in order to calculate time deltas in months or years we should use the relativedelta function.
Let’s use the same data as in the previous snippet to exemplify that:
from dateutil.relativedelta import relativedelta sign_date = datetime.date(2022,6, 7) notice_interval = relativedelta(months = 2) print('The expected start of this employee is: ' + str(sign_date+notice_interval))
Same result as expected:
The expected start of this employee is: 2022-08-07
Sum hours to a datetime in Python
In the same fashion, we are able to add hours to a Python datetime object. Let’s now calculate the expected takeoff time of our flight.
arrival_date = datetime.datetime (2002, 7, 8, 10,35) layover_lenght = datetime.timedelta(hours = 2) take_off = arrival_date + layover_lenght print('The expected takeoff time is: ' + str( take_off))
This will result in the following statement:
The expected takeoff time is: 2002-07-08 12:35:00