When working with dates in programming, the need often arises to add or subtract days from a given date. This article demonstrates a general solution for this task in Python, taking into account month-end scenarios.
In the provided code snippet, the developer attempted to add 5 days to a date using the following code:
<code class="python">EndDate = Date.today() + timedelta(days=10)</code>
However, this generated an error:
name 'timedelta' is not defined
To correctly add days to a date, the timedelta class from the datetime module should be utilized. Here's an improved version of the code:
<code class="python">import datetime StartDate = "10/10/11" # Example date Date = datetime.datetime.strptime(StartDate, "%m/%d/%y") EndDate = Date + datetime.timedelta(days=5)</code>
In this code, datetime.datetime.strptime converts the input string to a datetime object. Then, datetime.timedelta(days=5) creates a time delta representing 5 days. Finally, the operator adds the time delta to the Date object, producing the desired end date.
The above is the detailed content of How to Add Days to a Date in Python: A Solution for Month-End Scenarios. For more information, please follow other related articles on the PHP Chinese website!