How can I get the first day of the next month in Python?

Using dateutil you can do it the most literally possible:

import datetime
from dateutil import relativedelta
today = datetime.date.today()

next_month = today + relativedelta.relativedelta(months=1, day=1)

In English: add 1 month(s) to the today's date and set the day (of the month) to 1. Note the usage of singular and plural forms of day(s) and month(s). Singular sets the attribute to a value, plural adds the number of periods.

You can store this relativedelta.relativedelta object to a variable and the pass it around. Other answers involve more programming logic.

EDIT You can do it with the standard datetime library as well, but it's not so beautiful:

next_month = (today.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)

sets the date to the 1st of the current month, adds 32 days (or any number between 31 and 59 which guarantees to jump into the next month) and then sets the date to the 1st of that month.


Here is a 1-line solution using nothing more than the standard datetime library:

(dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)

Examples:

>>> dt = datetime.datetime(2016, 2, 29)
>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
2016-03-01 00:00:00

>>> dt = datetime.datetime(2019, 12, 31)
>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
2020-01-01 00:00:00

>>> dt = datetime.datetime(2019, 12, 1)
>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
2020-01-01 00:00:00

you can use calendar to get the number of days in a given month, then add timedelta(days=...), like this:

from datetime import date, timedelta
from calendar import monthrange

days_in_month = lambda dt: monthrange(dt.year, dt.month)[1]
today = date.today()
first_day = today.replace(day=1) + timedelta(days_in_month(today))
print(first_day)

if you're fine with external deps, you can use dateutil (which I love...)

from datetime import date
from dateutil.relativedelta import relativedelta

today = date.today()
first_day = today.replace(day=1) + relativedelta(months=1)
print(first_day)