【问题标题】:get last day of the month from year month in python [duplicate]在python中从年月获取本月的最后一天[重复]
【发布时间】:2015-10-26 19:29:56
【问题描述】:

我需要根据给定的 yearmonth 值获取一个月的第一天和最后一天。我能够得到第一天,我们如何在这里得到一个月的最后一天(在 python 中):

from datetime import date
def first_day_of_month(year,month):
    return date(year, month, 1)

print "Today: %s" % date.today()
print ("First day of this month: %s" %
first_day_of_month(2015,10))

这给出了输出: 今天:2015-10-26 本月的第一天:2015-10-01

如何获取当月的最后一天? P.s : 我不想将 31 作为 date() 函数的第三个参数。我想计算该月的天数,然后将其传递给函数。

【问题讨论】:

  • 那么你有什么尝试,它到底有什么问题?例如,为什么不从下个月的开始减去一天?
  • 我尝试了日历方法来获取月份范围,这样我可以做到,但我想使用日期函数,因为我在第一天使用它。 @Busturdust 建议的以下方法是我正在寻找的方法

标签: python date monthcalendar


【解决方案1】:

使用calendar.monthrange:

from calendar import monthrange
monthrange(2011, 2)
(1, 28)
# Just to be clear, monthrange supports leap years as well:

from calendar import monthrange
monthrange(2012, 2)
(2, 29)

“返回年、月的工作日 (0-6 ~ Mon-Sun) 和天数 (28-31)。”

【讨论】:

  • 你可能想解释一下monthrange的返回值:“返回年、月的工作日(0-6~Mon-Sun)和天数(28-31)。” (所以 OP 需要month_end = monthrange(year, month)[1]。)您的datetime 解决方案需要额外的逻辑来处理一年中的第一个月和最后一个月。我会省略它,因为monthrange 解决方案绰绰有余。另外,您有一个错字——from 之前有一个反引号。
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2012-12-16
  • 1970-01-01
相关资源
最近更新 更多