Hello!
How to create datetime object representing the very last moment of the current month ?
Hello!
How to create datetime object representing the very last moment of the current month ?
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.
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)