我想循环遍历给定开始时间以来的月份,并打印第一天和最后一天。我可以手动跟踪它是哪个月份和年份,并使用 calendar.monthrange(year, Month) 来获取天数......但这是最好的方法吗?
from datetime import date
start_date = date(2010, 8, 1)
end_date = date.today()
# I want to loop through each month and print the first and last day of the month
# 2010, 8, 1 to 2010, 8, 31
# 2010, 9, 1 to 2010, 9, 30
# ....
# 2011, 3, 1 to 2011, 3, 31
# 2011, 4, 1, to 2011, 4, 12 (ends early because it is today)
要查找一个月的最后一天,您可以使用first_of_next_month - datetime.timedelta(1)。例如:
def enumerate_month_dates(start_date, end_date):
current = start_date
while current <= end_date:
if current.month >= 12:
next = datetime.date(current.year + 1, 1, 1)
else:
next = datetime.date(current.year, current.month + 1, 1)
last = min(next - datetime.timedelta(1), end_date)
yield current, last
current = next
我是一名优秀的程序员,十分优秀!