Borislav Hadzhiev
Wed Jun 22 2022·2 min read
Photo by Alex Geerts
To add months to the current date in Python:
datetime.now()
method to get the current local date and time.relativedelta
object by passing the number of months to the
relativedelta
class.relativedelta
object.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.
python-dateutil
module installed, run the following command: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.
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.
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.
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 specific mini-language in expression blocks.