﻿ Python: Calculates the date six months from the current date - w3resource

# Python: Calculates the date six months from the current date

## Python Datetime: Exercise-26 with Solution

Write a Python program that calculates the date six months from the current date using the datetime module.

Sample Solution:

Python Code:

``````# Import the datetime module
import datetime

# Calculate the date 6 months from today's date and print it in ISO 8601 format
# The timedelta function is used to add a duration of 6 months to today's date (365 days in a year divided by 12 months)
# The result is then converted to ISO 8601 format using the isoformat() method
print((datetime.date.today() + datetime.timedelta(6 * 365 / 12)).isoformat())
```
```

Output:

```2017-11-04
```

Explanation:

In the exercise above,

• The code imports the datetime module.
• Calculating the future date:
• It calculates a future date by adding a 'timedelta' of 6 months to today's date.
• The "timedelta()" function from the "datetime" module is used to create a time duration of 6 months (6 * 365 / 12). This is an approximation where each month has 30.42 days on average.
• The result is added to today's date (datetime.date.today()).
• Formatting Date:
• The calculated future date is then converted to ISO 8601 format using the "isoformat()" method.
• Finally the ISO-formatted future date is printed to the console.

Flowchart:

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿