0

I have a SQL server stored procedure and I am trying to replicate it using python. One of the things I am trying to replicate is the following function:

DECLARE @Anchor_DT as DATE =EOMONTH(Getdate(),-1);

Here is what I have tried in Python3:

import datetime
datetime.date (2000, 3, 1) - datetime.timedelta (days = 1)

Output:

datetime.date(2000, 2, 29)

The thing is, I have to enter the date (200,3,1). I want to be able to pick up the current date and output the End of month. Here is what I tried but to no avail:

import datetime
datetime.date.now() - datetime.timedelta (days = 1)

Any suggestions or recommended solutions?

James Davinport
  • 303
  • 7
  • 19
  • 1
    Possible duplicate of [Get Last Day of the Month in Python](https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python) – bracco23 Jul 08 '19 at 15:20

1 Answers1

2

What about:

import datetime

now = datetime.datetime.today()
print(datetime.datetime((now.year + (now.month // 12)), (now.month + 1) % 12, 1) - datetime.timedelta(days = 1))

Or, you could use the calendar.monthrange method:

import calendar
import datetime

now = datetime.datetime.today()
_, lastday = calendar.monthrange(now.year, now.month)
print(datetime.datetime(now.year, now.month, lastday)) 
olinox14
  • 6,177
  • 2
  • 22
  • 39
  • For those looking at this later like I was, one warning: The top snippet does not work when today is in December. It results in month = 13, which gives the following error: `ValueError: month must be in 1..12` The second snippet should work, or you can add logic to round the number back to one if necessary. – Dave McGinnis Mar 19 '21 at 15:14