How do I calculate the date six months from the current date using the datetime Python module?



Python does not have a data type for dates, but we may import the datetime module to work with dates as date objects.

This article tells about how to display the current date by importing the datetime module.

Using relativedelta() function

The relativedelta type is intended to be applied to an existing datetime and can either indicate a period of time or replace specific elements of that datetime.

Example

The Python datetime module can be used to get the date six months from the current date. The code is shown below −

from datetime import date from dateutil.relativedelta import relativedelta # Adding six months to the current date and returning new date # Assigning the sum to six_months_from_now six_months_from_now = date.today() + relativedelta(months=+6) print(six_months_from_now)

Output

Following is an output of the above code −

2023-02-01

Example

Following is an alternate way of calculating the date six months from the current date using relativedelta() function −

from datetime import date from dateutil.relativedelta import relativedelta six_months_from_now = date(2022, 1, 8) + relativedelta(months=+6) print(six_months_from_now )

Output

Following is an output of the above code −

2022-07-08

Example

Following is an alternate way of calculating the date six months from the current date along with the timezone using relativedelta() function −

from datetime import datetime from dateutil.relativedelta import * six_months_from_now = datetime.now() print(six_months_from_now) six_months_from_now = datetime.now() + relativedelta(months=+6) print(six_months_from_now)

Output

Following is an output of the above code −

2022-11-10 12:39:06.305544
2023-05-10 12:39:06.305557

Using timedelta() fuction

A class in the datetime module that represents duration is called timedelta. The duration describes the difference between two date, datetime, or time instances whereas the delta denotes the average of the difference.

Example

You can also use the timedelta() function to get the date that will occur six months from the current date as follows −

import datetime print((datetime.date.today() + datetime.timedelta(6*365/12)).isoformat())

Output

Following is an output of the above code −

2023-05-11

Example

Following is an alternate way of calculating the date six months from the current date using timedelta() function −

import datetime current_day = datetime.date.today() print (current_day) six_months_from_now = current_day + datetime.timedelta(30*6) print (six_months_from_now)

Output

Following is an output of the above code −

2022-11-10
2023-05-09

Advertisements