>>> start_date = date(1983, 11, 23)
>>> start_date.replace(month=start_date.month+1)
datetime.date(1983, 12, 23)
This works until the month is <=11
, as soon as I do
>>> start_date = date(1983, 12, 23)
>>> start_date.replace(month=start_date.month+1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: month must be in 1..12
How can I keep adding months which increments the year when new month is added to December?
To add N months in a given date, create a relativedelta object representing the interval of N months and then add that to the datetime object to get the final date. Step 1: If the given date is in a string format, then we need to convert it to the datetime object. For that we can use the datetime. strptime() function.
In pandas, a string is converted to a datetime object using the pd. to_datetime() method. pd. DateOffset() method is used to add years to the created pandas object.
date(2020, 1, 1) today = datetime. date. today() for month in months_between(start_of_2020, today): print(month. strftime("%B %Y")) # January 2020, February 2020, March 2020, …
The dateutil library is useful for calculations like that:
>>> start_date + relativedelta(months=2)
datetime.date(1984, 1, 23)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With