【问题标题】:How to find number of days in the current month [duplicate]如何查找当月的天数[重复]
【发布时间】:2012-03-17 21:03:21
【问题描述】:

可能重复:
Get Last Day of the Month in Python

如何获取当月的天数?即,如果当前月份是“2012 年 1 月”,我应该得到 31。如果是“2012 年 2 月”,我应该得到 29。

【问题讨论】:

标签: python datetime


【解决方案1】:

正如彼得所说,calendar.monthrange(year, month) 返回工作日(0-6 ~ 周一至周日)和 yearmonth 的天数(28-31)。

>>> import calendar
>>> print calendar.monthrange(2012,1)[1]
31
>>> calendar.monthrange(2012,2)[1]
29

编辑:更新答案以返回当月的天数

>>> import calendar
>>> import datetime
>>> now = datetime.datetime.now()
>>> print calendar.monthrange(now.year, now.month)[1]
29

【讨论】:

  • 谢谢!!!!但我不想硬编码日期,如 (2012,1)..我希望它是系统日期
  • 非常感谢。这适用于 windows..我使用的是 ubuntu 11.10..并且导入日历会产生错误“没有名为日历的模块”..有什么想法吗???还是有其他方法可以在不使用“日历”的情况下完成这项工作???
  • 注意,是calendAr而不是calendEr
猜你喜欢
  • 2022-07-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2013-10-29
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多