Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 523
Flux Avatar asked Aug 05 '19 07:08

Flux


People also ask

How do I get the last day of the next month in Python?

Method #1 : Using replace() + timedelta() In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.

How do you get the first day of the week in Python?

You can use the calender module to get the first day of the week using Python. The calender module has a special function, firstweekday(), that returns the current setting for the weekday to start each week.


1 Answers

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
like image 151
Toby Petty Avatar answered Oct 06 '22 00:10

Toby Petty