Search code examples
pythonpython-datetime

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


How can I get the first date of the next month in Python? For example, if it's now 2019-12-31, the first day of the next month is 2020-01-01. If it's now 2019-08-01, the first day of the next month is 2019-09-01.

I came up with this:

import datetime

def first_day_of_next_month(dt):
    '''Get the first day of the next month. Preserves the timezone.

    Args:
        dt (datetime.datetime): The current datetime

    Returns:
        datetime.datetime: The first day of the next month at 00:00:00.
    '''
    if dt.month == 12:
        return datetime.datetime(year=dt.year+1,
                                 month=1,
                                 day=1,
                                 tzinfo=dt.tzinfo)
    else:
        return datetime.datetime(year=dt.year,
                                 month=dt.month+1,
                                 day=1,
                                 tzinfo=dt.tzinfo)


# Example usage (assuming that today is 2021-01-28):
first_day_of_next_month(datetime.datetime.now())
# Returns: datetime.datetime(2021, 2, 1, 0, 0)

Is it correct? Is there a better way?


Solution

  • 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