Python: how to add a 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 as long as the month <=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 add months that increase the year when a new month is added in December?

+4
source share
5 answers

The dateutil library is useful for such calculations:

 >>> start_date + relativedelta(months=2) datetime.date(1984, 1, 23) 
+9
source
 try: start_date.replace(month=start_date.month+1) except ValueError: if start_date.month == 12: start_date.replace(month=1) start_date.replace(year=start_date.year+1) else: raise 
+2
source

Using datetime.timedelta and calendar.monthrange :

 >>> from datetime import date, timedelta >>> import calendar >>> start_date = date(1983, 12, 23) >>> days_in_month = calendar.monthrange(start_date.year, start_date.month)[1] >>> start_date + timedelta(days=days_in_month) datetime.date(1984, 1, 23) 
+2
source

You will need to decide how you want to deal with such strange cases as January 31 + 1 month = February 31 (which does not exist). But I tend to use timedelta to add to your date, as in:

 import datetime as dt dt.datetime.now() + dt.timedelta(days=30) 

Where you can choose days based on the size of the current or next month, or some other value so that you do not overflow the next month.

+1
source

If you want to have a more general solution to this problem, for example. adding days, months and years mixed with one date:

 import time, datetime, calendar def upcount(dt, years=0, months=0, **kwargs): if months: total_months = dt.month + months month_years, months = divmod(total_months, 12) if months == 0: month_years -= 1 months = 12 years += month_years else: months = dt.month years = dt.year + years try: dt = dt.replace(year=years, month=months) except ValueError: # 31st march -> 31st april gives this error max_day = calendar.monthrange(years, months)[1] dt = dt.replace(year=years, month=months, day=max_day) if kwargs: dt += datetime.timedelta(**kwargs) return dt 
0
source

Source: https://habr.com/ru/post/1437895/


All Articles