如何获得每月的最后一天? [英] How to get the last day of the month?

查看:69
本文介绍了如何获得每月的最后一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Python的标准库轻松确定(即调用一个函数)给定月份的最后一天?

Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

如果标准库没有

推荐答案

我早些时候在看日历模块的href = https://docs.python.org/3/library/calendar.html rel = noreferrer>文档,但是称为 monthrange 提供以下信息:

I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:


monthrange(年,月)

  ;  返回指定年份和月份的每月第一天的工作日以及每月的天数。

monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.



>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)

so:

calendar.monthrange(year, month)[1]

似乎是最简单的方法。

请注意, monthrange 也支持leap年:

Just to be clear, monthrange supports leap years as well:

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

我之前的答案仍然有效,但显然不是最佳选择。

My previous answer still works, but is clearly suboptimal.

这篇关于如何获得每月的最后一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆