3 examples of 'python datetime add month' in Python

Every line of 'python datetime add month' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
157def AddMonths(start_date, months):
158 """A simple convenience utility for adding months to a given start date.
159
160 This increments the months by adding the number of days in the current month
161 to the current month, for each month.
162
163 Args:
164 start_date: date The date months are being added to.
165 months: int The number of months to add.
166
167 Returns:
168 A date equal to the start date incremented by the given number of months.
169 """
170 current_date = start_date
171 i = 0
172 while i < months:
173 month_days = calendar.monthrange(current_date.year, current_date.month)[1]
174 current_date += timedelta(days=month_days)
175 i += 1
176 return current_date
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

69def add_month_based_on_weekday(date):
70 # Is the weekday of this date the last one?
71 is_last_weekday = (date + datetime.timedelta(weeks=1)).month != date.month
72
73 # Some magic which pushes and pulls some weeks until
74 # it fits right.
75 new_date = date + datetime.timedelta(weeks=4)
76 if (new_date.day + 6) // 7 < (date.day + 6) // 7:
77 new_date += datetime.timedelta(weeks=1)
78 next_month = add_month(date, override_day=1)
79 if new_date.month == (next_month.month - 1 if next_month.month > 1 else 12):
80 new_date += datetime.timedelta(weeks=1)
81 elif new_date.month == (next_month.month + 1 if next_month.month < 12 else 1):
82 new_date += datetime.timedelta(weeks=-1)
83
84 # If the weekdate of the original date was the last one,
85 # and there is some room left, add a week extra so this
86 # will result in a last weekday of the month again.
87 if is_last_weekday and (new_date + datetime.timedelta(weeks=1)).month == new_date.month:
88 new_date += datetime.timedelta(weeks=1)
89
90 return new_date
33def test_add_month_with_overflow():
34 assert pendulum.datetime(2012, 1, 31).add(months=1).month == 2

Related snippets