Python: Subtract five days from current date
Python datetime: Exercise-5 with Solution
Write a Python program to subtract five days from the current date.
Sample Solution:
Python Code:
# Import the date class and the timedelta class from the datetime module
from datetime import date, timedelta
# Calculate the date 5 days before today's date
dt = date.today() - timedelta(5)
# Print the current date using date.today()
print('Current Date :', date.today())
# Print the date calculated 5 days before the current date
print('5 days before Current Date :', dt)
Output:
Current Date : 2017-05-05 5 days before Current Date : 2017-04-30
Explanation:
In the exercise above,
- The code imports the "date" class and the "timedelta" class from the "datetime" module.
- Next it calculates the date that occurred 5 days before the current date (date.today()) using the "timedelta" class. This is done by subtracting a "timedelta" object of 5 days from the current date.
- Finally it prints two lines:
- The current date is printed using "date.today()".
- The date calculated 5 days before the current date is printed using the previously calculated "dt".
Flowchart:
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to get the current time.
Next: Write a Python program to convert unix timestamp string to readable date.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/date-time-exercise/python-date-time-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics