Files
Python_CookBook_repo/3.数字日期和时间/14.找出当月日期范围.py
2025-09-10 16:12:45 +08:00

34 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime, date, timedelta
import calendar
from fontTools.misc.plistlib import end_date
if __name__ == "__main__":
def get_month_range(start_date=None):
if start_date is None:
start_date = date.today().replace(day=1)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
end_date = start_date + timedelta(days = days_in_month)
return start_date, end_date
a_day = timedelta(days=1)
first_day, last_day = get_month_range()
while first_day < last_day:
print(first_day)
first_day = first_day + a_day
# 在获取一个月天数的时候calendar库会非常好用monthrange会返回第一个工作日的日期和当月的天数
# 如果想要实现和Python内建的range一样的遍历效果可以写一个生成器
def date_range(start_date, end_date, step=timedelta(days=1)):
while start_date < end_date:
yield start_date
start_date += step
for d in date_range(first_day, last_day):
print(d)