Konstantin
Konstantin

Reputation: 6131

python's datetime and end of the month

How to create datetime object representing the very last moment of the current month ?

Upvotes: 4

Views: 3557

Answers (3)

KravAn
KravAn

Reputation: 306

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

where 'timedelta(days=1)' might be a difference with next month and last moment of the previous month.

Upvotes: 0

tzot
tzot

Reputation: 95911

import datetime

def eom(dt):
    sometime_next_month= dt.replace(day=1) + datetime.timedelta(days=31)
    start_of_next_month= sometime_next_month.replace(day=1,hour=0,minute=0,second=0)
    return start_of_next_month - datetime.timedelta(seconds=1)


>>> eom(datetime.datetime(1972, 2, 1, 23, 50, 50))
datetime.datetime(1972, 2, 29, 23, 59, 59)
>>> eom(datetime.datetime(1980, 12, 31))
datetime.datetime(1980, 12, 31, 23, 59, 59)

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328564

Use a simple trick: Set the date to the first of the next month and then subtract one second/hour/day/as much as you need.

Upvotes: 17

Related Questions