我想在给定的开始时间之后循环几个月,并打印第一天和最后一天。我可以手动跟踪它是哪个月份和年份,并使用calendar.monthrange(年,月)来获取天数......但这是最好的方法吗?
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)
答案 0 :(得分:1)
要查找一个月的最后一天,您可以使用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
答案 1 :(得分:0)
dateutil模块支持此类操作,请参阅:http://niemeyer.net/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57
答案 2 :(得分:0)
嗯,在公历中,任何月份的第一天编号为1,最后一天是下个月的第一天减1。因此,以最微不足道的形式:
d = datetime.date(2010, m, 1)
print d, datetime.date(2010, m + 1, 1) - datetime.timedelta(days=1)
(这在12月不起作用,因为date()的月份参数需要在1..12)
答案 3 :(得分:0)
这有效:
#!/usr/bin/python
from datetime import date, timedelta
import calendar
start_date = date(2001,8,1)
end_date = date.today()
while True:
if start_date > end_date:
break
days_in_month = calendar.monthrange(start_date.year, start_date.month)[1] # Calculate days in month for start_date
new_ts = calendar.timegm(start_date.timetuple()) + (days_in_month * 24 * 60 * 60) # Get timestamp for start of next month
new_start_date = date(1,1,1).fromtimestamp(new_ts) # Convert timestamp to date object
print start_date, new_start_date - timedelta(1)
start_date = new_start_date