2010-11-01 89 views
1

我有一個對象的列表,其中包括一個日期,其中包括一個日期,我需要創建一個列表中的所有對象,該日期隨時間月,即上月1日午夜<目標數據<本月1日午夜。根據兩個日期時間之間的事件刪除列表

我還需要滿足此條件的總對象數。

現在,我要它在一系列while循環,但我覺得必須有一個更好的辦法,特別是因爲我的腳本掛起:

 post = 0 #the current post we're analyzing 
     posts = 0 #the total number of posts in the month we actually care about 
     lastmonthposts = [] #I think i can just get rid of this 
     blog = pyblog.WordPress() 

     date = blog.get_recent_posts(1 + posts)[0]['dateCreated'] 
     while (date > startthismonth): 
      print "So far, there have been " + str(posts) + " posts this month we've counted." 
      post = post + 1 
      date = blog.get_recent_posts(1 + post)[0]['dateCreated'] 
     while (date > startlastmonth): 
      print "So far, there have been " + str(posts) + " posts last month we've counted, which is " + str(date.timetuple().tm_mon) + "." 
      posts = posts + 1 
      post = post + 1 
      date = blog.get_recent_posts(1 + post)[0]['dateCreated'] 
      lastmonthposts.append('blog') 
     for blogpost in lastmonthposts: 
      postnumber = blogpost['postid'] 
      comments = comments + int(blog.get_comment_count(postnumber)['approved']) 

回答

2

而不是get_recent_posts()我會使用get_page_list()

from datetime import datetime, timedelta 

this_month_start = datetime.now().date().replace(day=1) 
prev_month_start = (this_month_start - timedelta(days=1)).replace(day=1) 

pages = blog.get_page_list() 
last_month_pages = [ 
    p for p in pages 
    if prev_month_start <= p['dateCreated'] < this_month_start] 
last_month_approved_comment_count = sum(
    blog.get_comment_count(page['page_id'])['approved'] 
    for page in last_month_pages) 

print "number of last month's pages:", len(last_month_pages) 
print "number of approved comments for last month's pages:", 
print last_month_approved_comment_count 
+0

感謝君士坦丁,這絕對簡單得多。我不明白你爲什麼建議get_page_list(),雖然有新的博客文章,但似乎只返回「0」,因此沒有新的頁面。努力重新配置它以使用帖子,然後我會標記您接受。 – 2010-11-02 03:17:13

+0

@Michael Morisy,嗯,我的印象是「後」和「頁」在API中意味着相同的東西。這是一個錯誤的假設?你確定'blog.get_page_list()'返回「0」嗎?你可以在'pages = blog.get_page_list()'之後插入'print pages'並檢查輸出嗎? – Constantin 2010-11-02 08:34:42

+0

非常感謝您的回覆。不,在WP中處理帖子和頁面的方式不同。我再次檢查您的打印建議,並打印關於頁面。然而,用pages = blog.get_recent_posts()代替它會打印出我想看的材料,但即使該打印命令打印出正確的文章,我仍然可以獲得全0。去檢查看看我是否看錯了日期。 – 2010-11-02 13:36:36

相關問題