How to create datetime object representing the very last moment of the current month ?
Asked
Active
Viewed 3,349 times
4
-
what precision are you looking for? – SilentGhost Nov 02 '09 at 16:01
-
1 second would be enough – Konstantin Nov 02 '09 at 16:02
-
Longer discussion: [How to get the last day of the month?](https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month/14994380) – Shadi Dec 01 '22 at 14:47
3 Answers
17
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.

Aaron Digulla
- 321,842
- 108
- 597
- 820
-
1+1: Always works -- never needs to know number of days in the month. Or year, for that matter. – S.Lott Nov 02 '09 at 16:03
1
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)

tzot
- 92,761
- 29
- 141
- 204
-
1
-
You're right. I had the impression that datetime.datetime was doing the *right thing*, but obviously I was wrong. I'll find the code I've written in another answer in SO. – tzot Nov 02 '09 at 22:21
0
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.

KravAn
- 186
- 1
- 12