2011-04-12 44 views
1

我想循環使用自給定開始時間以來的月份,並打印第一天和最後一天。我可以手動記錄月份和年份,並使用calendar.monthrange(year,month)來獲取天數......但這是最好的方法嗎?從開始時間開始通過python月循環

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) 

回答

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 
0

那麼,在公曆,任何一個月的第一天被編號爲1,最後一天是在下月減一。因此,在其最瑣碎的形式:

d = datetime.date(2010, m, 1) 
print d, datetime.date(2010, m + 1, 1) - datetime.timedelta(days=1) 

(這並不十二月工作作爲月份參數日期()需要在1..12)

0
  1. 先從開始日期的第一天,在這一個月的天
  2. 計算數量和獲得下個月開始
  3. 打印起始日期和下月(開始 - 1天)

這工作:

#!/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