Add months to the current date in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Add months to the current date in Python #

To add months to the current date in Python:

  1. Use the datetime.now() method to get the current local date and time.
  2. Create a relativedelta object by passing the number of months to the relativedelta class.
  3. Sum the current date and the relativedelta object.
main.py
from datetime import datetime from dateutil.relativedelta import relativedelta now = datetime.now() print(now) # 👉️ 2022-06-22 19:27:37.483564 result = now + relativedelta(months=+3) print(result) # 👉️ 2022-09-22 19:27:37.483564

We used the datetime.now method to get the current local date and time.

Make sure to import the relativedelta and the datetime classes.

If you don't have the python-dateutil module installed, run the following command:
shell
pip install python-dateutil

Notice that we prefixed the number of months with a plus + to indicate that we want to add the specified number of months.

The relativedelta class automatically handles months with different numbers of days and adding one months never crosses the month boundary.

If necessary, the year will be rolled over automatically (e.g. adding 6 months to a date in September).

If you only need to extract the date after the operation, call the date() method on the datetime object.

main.py
from datetime import datetime from dateutil.relativedelta import relativedelta now = datetime.now() print(now) # 👉️ 2022-06-22 19:27:37.483564 result = now + relativedelta(months=+3) print(result) # 👉️ 2022-09-22 19:27:37.483564 # 👇️ only extract updated date print(result.date()) # 👉️ 2022-09-22

The datetime.date method returns a date object with the same year, month and day.

If you need to format the date in a certain way, use a formatted string literal.

main.py
from datetime import datetime from dateutil.relativedelta import relativedelta now = datetime.now() print(now) # 👉️ 2022-06-22 19:34:48.991786 result = now + relativedelta(months=+5) print(result) # 👉️ 2022-11-22 19:34:48.991786 # 👇️ only extract updated date print(result.date()) # 👉️ 2022-11-22 print(f'{result:%Y-%m-%d %H:%M:%S}') # 👉️ 2022-11-22 19:34:48

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.