Adding months to a Python date object
You can use the dateutil.relativedelta function in order to append an arbitratry number of months to a Python datetime object. The code below adds 2 months to a date:
new_date = datetime.date (2023,1, 5) + relativedelta(months = 2)
Incrementing a date object in Python – example
Our task for today will be to sum an arbitrary number of months (or years) to our datetime object in Python.
Consider the following script:
import datetime
from dateutil.relativedelta import relativedelta
start_date = datetime.date (2023,1, 5)
end_date_delta = relativedelta(months = 2)
print('The expected end date of the hiring campaign is on : ' + str(start_date + end_date_delta))
The result will be:
The expected end date of the hiring campaign is on : 2023-04-05
Sum a month to the current date
We can use a similar technique to add a number of months to the current time / date:
one_month_from_today = (datetime.date.today() + relativedelta(month = 1)).strftime('%y-%m-%d')
Increment a datetime by a floating number
The relativedelta function doesn’t allow to increment months and years by a floating number. Let’s take a look:
tart_date = datetime.date (2023,1, 5)
end_date_delta = relativedelta(months = 2.54)
print('The expected end date of the hiring campaign is on : ' + str(start_date + end_date_delta))
This will result in a ValueError exception:
ValueError: Non-integer years and months are ambiguous and not currently supported.
A good enough solution could be to use the timedelta library and add the number of days; alternatively.
start_date = datetime.date (2023,1, 5)
end_date = start_date + datetime.timedelta(int(3.54*30))
print('The expected end date of the hiring campaign is on : ' + str(end_date))
Sum months to a Pandas DataFrame column
In this next example, we will create a new pandas DataFrame column that will contain the values of the timestamps / datetimes which we augmented.
import pandas as pd
dates = pd.Series(pd.date_range(start='4/1/24', end = '4/12/24', freq='B'))
sales = [3011, 3245, 3128, 2416, 3236, 2412, 3043, 2357, 3302, 2731]
sales_df = pd.DataFrame(dict(dates = dates, sales = sales))
We will now going to create a new column, representing the warranty end date for our product, specifically 2 months from the sales date. In order to do that, we will use the DateOffset method of the pd.tseries library. We could as well use the np.timedelta() method of the Numpy library.
sales_df['warranty_end_date'] = sales_df['dates'] + pd.tseries.offsets.DateOffset(months = 2)
This will render the following data:
dates | sales | warranty_end_date | |
---|---|---|---|
0 | 2024-04-01 | 3011 | 2024-06-01 |
1 | 2024-04-02 | 3245 | 2024-06-02 |
2 | 2024-04-03 | 3128 | 2024-06-03 |
3 | 2024-04-04 | 2416 | 2024-06-04 |
4 | 2024-04-05 | 3236 | 2024-06-05 |
5 | 2024-04-08 | 2412 | 2024-06-08 |
6 | 2024-04-09 | 3043 | 2024-06-09 |
7 | 2024-04-10 | 2357 | 2024-06-10 |
8 | 2024-04-11 | 3302 | 2024-06-11 |
9 | 2024-04-12 | 2731 | 2024-06-12 |