Write a Python program to get the dates 30 days before and after from the current date


The program is written in the Python programming language and uses the datetime module to work with dates and times. It calculates the current date, 30 days before the current date, and 30 days after the current date, and then prints the results. Here's a breakdown of the code:

  • The first line imports the "date" and "timedelta" classes from the datetime module. These classes are used to represent dates and time durations, respectively.
  • The next line uses the "date.today()" method to get the current date and the "isoformat()" method to convert it to a string in ISO format (yyyy-mm-dd). This result is stored in the "cd" variable.
  • The next line calculates the date 30 days before the current date by subtracting a "timedelta" object with a value of 30 days from the current date. The result is again converted to a string in ISO format using the "isoformat()" method and stored in the "before" variable.
  • The next line calculates the date 30 days after the current date by adding a "timedelta" object with a value of 30 days to the current date. The result is stored in the "after" variable in the same way as before.
  • The last two lines use the "print()" function to display the results. The "Current Date" and the "30 Days Before Current Date" are printed along with their respective values, and the same goes for the "30 Days After Current Date".

The program can be used to calculate and display dates in a specified format, which can be useful in various applications, such as event scheduling, project management, and more.

Source Code

from datetime import date, timedelta
 
cd = date.today().isoformat()   
before = (date.today()-timedelta(days=30)).isoformat()
after = (date.today()+timedelta(days=30)).isoformat()  
 
print("Current Date: ",cd)
print("30 Days Before Current Date: ",before)
print("30 Days After Current Date : ",after)

Output

Current Date:  2022-09-24
30 Days Before Current Date:  2022-08-25
30 Days After Current Date :  2022-10-24

Example Programs