views:

138

answers:

2

Hello!

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

+12  A: 

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
+1: Always works -- never needs to know number of days in the month. Or year, for that matter.
S.Lott
+1  A: 
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)
ΤΖΩΤΖΙΟΥ
why are you discriminating December?
SilentGhost
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.
ΤΖΩΤΖΙΟΥ