Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : How to add month to December 2012 and get January 2013?

>>> 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?

like image 895
daydreamer Avatar asked Oct 04 '12 21:10

daydreamer


People also ask

How do you add months to a date in Python?

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.

How do you increment a year in Python?

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.

How do I get the month between two dates in Python?

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, …


1 Answers

The dateutil library is useful for calculations like that:

>>> start_date + relativedelta(months=2)
datetime.date(1984, 1, 23)
like image 77
Daniel Roseman Avatar answered Oct 03 '22 12:10

Daniel Roseman