Python 根据介于两个日期时间之间的事件缩减列表
我有一个对象列表,其中包括一个日期,我需要创建一个列表,列出上个月任何时候该日期所在的所有对象,即上个月1日午夜<目标数据<本月1日午夜 我还需要满足此条件的对象总数 现在,我正在进行一系列while循环,但我觉得必须有更好的方法,特别是因为我的脚本挂起:Python 根据介于两个日期时间之间的事件缩减列表,python,datetime,python-datetime,Python,Datetime,Python Datetime,我有一个对象列表,其中包括一个日期,我需要创建一个列表,列出上个月任何时候该日期所在的所有对象,即上个月1日午夜
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'])
我将使用
获取页面列表()
,而不是获取最近的帖子()
:
从datetime导入datetime,timedelta
本月开始=datetime.now().date().replace(day=1)
上个月开始=(本月开始-时间增量(天=1))。替换(天=1)
pages=blog.get_page_list()
上个月的页数=[
页中的p对p
如果上个月开始感谢Constantin,这肯定简单多了。我不明白你为什么建议获取页面列表(),它似乎只返回“0”因为虽然有新的博客帖子,但没有新的页面。正在将其重新配置为使用帖子,然后我会将您标记为已接受。@Michael Morisy,嗯,我的印象是“post”和“page”在API中的含义相同。这是错误的假设吗?您确定blog.get\u page\u list()
返回“0”吗?你能在pages=blog之后插入print pages
吗?获取页面列表()
并检查输出?非常感谢你回来检查。不,WP中的帖子和页面处理方式不同。我仔细检查了你的打印建议,它打印了关于页面。将其替换为pages=blog。获取最近的帖子()
,但是,打印出了我想要查看的资料,但是即使打印命令打印出了正确的帖子,我仍然得到了所有的0。去检查一下我是否看错了日期。好的,解决了问题。它比较了两种不同的时间格式,2010-11-01和20100326T06:52:17。谢谢@Constantin的所有帮助。
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