0

Python: Getting last day of the month from a given date

If you were tasked to get the last day of the month from a given date. Here is a quick solution I’ve found and modified little bit:

from datetime import datetime, timedelta

# https://stackoverflow.com/a/43088
def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31).strftime("%Y-%m-%d")
    return (date.replace(month=date.month+1, day=1) - timedelta(days=1)).strftime("%Y-%m-%d")


print(last_day_of_month(datetime(2022,6,3)))
# or 
print(last_day_of_month(datetime.now()))

a snippet of code above will print the following result:

C:\python>python last_day.py
2022-06-30
2022-07-31

 

Kevin San Jose, VCP6-DCV

Kevin San Jose, VCP6-DCV

LFCS, MTCRE, VCP6-DCV

Leave a Reply

Your email address will not be published. Required fields are marked *