gpt4 book ai didi

python - 自开始时间以来循环遍历 python 月份

转载 作者:太空宇宙 更新时间:2023-11-03 19:31:28 29 4
gpt4 key购买 nike

我想循环遍历给定开始时间以来的月份,并打印第一天和最后一天。我可以手动跟踪它是哪个月份和年份,并使用 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

关于python - 自开始时间以来循环遍历 python 月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5641685/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com