简体   繁体   English

如何使用 Python3 获取当前日期的 EOMONTH(月末)

[英]How to get the EOMONTH(End of month) of the current date using Python3

I have a SQL server stored procedure and I am trying to replicate it using python.我有一个 SQL 服务器存储过程,我正在尝试使用 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:这是我在 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).问题是,我必须输入日期(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?任何建议或推荐的解决方案?

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:或者,您可以使用calendar.monthrange方法:

import calendar
import datetime

now = datetime.datetime.today()
_, lastday = calendar.monthrange(now.year, now.month)
print(datetime.datetime(now.year, now.month, lastday)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM