如何在python中获取当月的第一天和最后一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36155332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:29:19  来源:igfitidea点击:

how to get the first day and last day of current month in python

python

提问by AKHIL MATHEW

I am writing an SQL query to get the available data between the first date and last date of the current month in python. For this how can I get first and last date of current month.

我正在编写一个 SQL 查询来获取 python 中当月的第一个日期和最后一个日期之间的可用数据。为此,我如何获得当月的第一个和最后一个日期。

Note: In the question that already asked in stackoverflow only deals with end date. Also, I want the answer as a date field like 01-03-2016 or 31-03-2016.

注意:在 stackoverflow 中已经提出的问题中,只涉及结束日期。另外,我希望将答案作为日期字段,例如 01-03-2016 或 31-03-2016。

回答by bakkal

how to get the first day and last day of current month in python

如何在python中获取当月的第一天和最后一天

There's a function in the standard library calendar.monthrange(year, month):

标准库中有一个函数calendar.monthrange(year, month)

>>> import calendar
>>> calendar.monthrange(2016, 3)
(1, 31)

Careful, monthrangedoesn'treturn the dates of first and last days, but returns the weekday of the first day of the month, and number of days in month, for the specified year and month.

注意monthrange返回第一天和最后一天的日期,而是返回指定年月第一天的工作日和月中的天数。

So to create first and last dateobjects, use 1for the first day, and the number of days for the second day:

所以要创建第一个和最后一个date对象,第一天使用1,第二天使用天数:

>>> _, num_days = calendar.monthrange(2016, 3)
>>> first_day = datetime.date(2016, 3, 1)
>>> last_day = datetime.date(2016, 3, num_days)
>>> first_day
datetime.date(2016, 3, 1)
>>> last_day
datetime.date(2016, 3, 31)

Formatting these as strings:

将这些格式化为字符串:

>>> first_day.strftime('%Y-%m-%d')
'2016-03-01'
>>> last_day.strftime('%Y-%m-%d')
'2016-03-31'