通过年和月,获得一个月中的第一天和最后一天的日期

from datetime import datetime, timedelta
def day_of_month(year, month):
    str_from = '%s-%s-1 00:00:00' % (year, month)
    dt_from = datetime.strptime(str_from, "%Y-%m-%d %H:%M:%S")
    any_day = date(dt_from.year, dt_from.month, dt_from.day)
    next_month = any_day.replace(day=28) + timedelta(days=4)
    str_to = next_month - timedelta(days=next_month.day)
    str_to = '%s 23:59:59' % str_to
    dt_to = datetime.strptime(str_to, "%Y-%m-%d %H:%M:%S")
    return datetime.date(dt_from),datetime.date(dt_to)
one_day, end_day = day_of_month(2020, 12)
原文地址:https://www.cnblogs.com/ghh520/p/13588741.html