繁体   English   中英

如何在Python中根据年和月检查日期

[英]How to check dates basing on year and month in Python

我想查一下给定月份的日子。 例如,如果我输入2017年和第2个月或2月,则希望接收该月的所有日期,在这种情况下为01-28.02.2017。

可以用Python做吗? 正在尝试使用Google查找内容,但未成功。

提前致谢,

在标准库中有一个函数: itermonthdates()

from calendar import Calendar

for date in Calendar().itermonthdates(2017, 2):
    print(date)

您可能需要使用if date.month == 2来过滤日期,因为if date.month == 2日期属于同一周,它将包含前几个月和if date.month == 2的日期。

就像Mark在评论中建议的那样,如果您知道月份,则可以自己进行操作。

import calendar

year, month = 2017, 2

def days_in_month(date):
    if calendar.isleap(date.year) and date.month == 2:
        return 29
    else:
        return [None, 31, 28, 31, 30, 31, 30, ...][date.month]

date = datetime.date(year=year, month=month)

dates = [datetime.date(year=year, month=month, day=d) for d in range(1, days_in_month(date)+1)]

暂无
暂无

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

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