从开始时间循环遍历Python月份
我想从一个指定的开始时间开始,循环遍历每个月,并打印出每个月的第一天和最后一天。我可以手动记录现在是哪个月和哪一年,然后用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)
4 个回答
0
dateutil模块确实支持这样的操作,具体可以查看这里:http://niemeyer.net/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57
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
3
要找出一个月的最后一天,你可以用下个月的第一天减去一天。比如说:
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