w3resource

Python: Calculates the date six months from the current date


26. Six Months Later

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:

Flowchart: Calculates the date six months from the current date.

For more Practice: Solve these Related Problems:

  • Write a Python program to calculate the date exactly six months from today and then display the day of the week for that future date.
  • Write a Python script to compute the date six months ahead and adjust for cases where the resulting day might not exist (e.g., August 31).
  • Write a Python function to add six months to a given date and then format the result in "Month DD, YYYY" format.
  • Write a Python program to determine the date six months from a user-provided date and then compare it with the same day last year.

Previous: Write a Python program to print a string five times, delay three seconds.
Next: Write a Python program to create 12 fixed dates from a specified date over a given period. The difference between two dates will be 20.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.