Python: Add a month with a specified date
Python Datetime: Exercise-23 with Solution
Write a Python program to add a month to a specified date.
Sample Solution:
Python Code:
# Import the date and timedelta classes from the datetime module
from datetime import date, timedelta
# Import the calendar module
import calendar
# Define the start date as December 25, 2014
start_date = date(2014, 12, 25)
# Get the number of days in the month of the start date's year and month
# The monthrange() function returns a tuple containing the weekday of the first day of the month
# and the number of days in the month, and we access the second value ([1]) which represents the number of days
days_in_month = calendar.monthrange(start_date.year, start_date.month)[1]
# Print the date obtained by adding the number of days in the month to the start date
print(start_date + timedelta(days=days_in_month))
Output:
2015-01-25
Explanation:
In the exercise above,
- The code imports the "date" and "timedelta" classes from the "datetime" module. It also imports the "calendar" module.
- Defined start date:
- It defines a variable 'start_date' with the value representing December 25, 2014.
- Calculating days in the month:
- It uses the "monthrange()" function from the "calendar" module to determine the number of days in the month of the start date's year and month.
- The "monthrange()" function returns a tuple containing the weekday of the first day of the month and the number of days in the month. By accessing the second value of this tuple, it retrieves the number of days in the month.
- Calculating the end date:
- It calculates the end date by adding the number of days in the month to the start date using timedelta(days=days_in_month).
- It prints the calculated end date.
Flowchart:
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to get the number of days of a given month and year.
Next: Write a Python program to count the number of Monday of the 1st day of the month from 2015 to 2016.
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-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics