Search code examples
pythonpython-3.xdatedatetimemonthcalendar

Get the last day of next month in Python


How to calculate the last day of next month or next 4 months in Python?

I tried datetime, however, it does not support opperation of +.

To reopen my question.

    datetime.datetime.today() + datetime.datetime.date(2019,4,20).month

this is helpful because if I want to get the last day of next 4 months from 2019-12-30. Then the year will change too.

I want to reopen this because one of the answers is surprising. I did not know np can output dates. Cool answer.


Solution

  • Does this answer your question?

    import numpy as np
    
    # display last day of Dezember, 2019
    print(np.arange('2019-12', '2020-01', dtype='datetime64[D]')[-1])
    
    # add a month to Dezemeber, 2019
    np.datetime64('2019-12') + np.timedelta64(1, 'M')