Skip to main content
 首页 » 编程设计

python之按月过滤日期时间对象中的日期

2025年01月19日27leader

我有一个字典,其中键是 datetime.datetime,值是推文列表。所以它看起来像这样:

{datetime.datetime(2017, 9, 30, 19, 55, 20) : ['this is some tweet text'], 
 datetime.datetime(2017, 9, 30, 19, 55, 20) : ['this is another tweet']... 

我正在尝试获取一年中每个月发送的推文数量。到目前为止我已经...

startDate = 10 
endDate= 11 
start = True 
while start: 
 
    for k,v in tweetDict.items(): 
        endDate-=1 
        startDate-=1 
 
        datetimeStart = datetime(2017, startDate, 1) 
        datetimeEnd = datetime(2017,endDate, 1) 
 
        print(datetimeStart, datetimeEnd) 
 
        if datetimeStart < k < datetimeEnd: 
            print(v) 
        if endDate == 2: 
            start = False 
            break 

只打印(我知道打印语句)...

2017-08-01 00:00:00 2017-09-01 00:00:00 
2017-07-01 00:00:00 2017-08-01 00:00:00 
2017-06-01 00:00:00 2017-07-01 00:00:00 
2017-05-01 00:00:00 2017-06-01 00:00:00 
2017-04-01 00:00:00 2017-05-01 00:00:00 
2017-03-01 00:00:00 2017-04-01 00:00:00 
2017-02-01 00:00:00 2017-03-01 00:00:00 
2017-01-01 00:00:00 2017-02-01 00:00:00 

而不是实际的推文本身。我期待的是……

2017-08-01 00:00:00 2017-09-01 00:00:00 
['heres a tweet'] 
['theres a tweet'] 
2017-07-01 00:00:00 2017-08-01 00:00:00 
['there only 1 tweet for this month'].... 

我有点卡住了,我该如何实现?

请您参考如下方法:

你可以 group by月份而不是尝试减去/比较不同的月份:

>>> d = {datetime.datetime(2017, 9, 30, 19, 55, 20): ['this is some tweet text'], 
         datetime.datetime(2017, 9, 30, 20, 55, 20): ['this is another tweet'], 
         datetime.datetime(2017, 10, 30, 19, 55, 20): ['this is an october tweet'],} 
>>> from itertools import groupby 
>>> for month, group in groupby(d.items(), lambda (k, v): k.month): 
...     print(month) 
...     for dt, tweet in group: 
...         print(dt, tweet) 
...          
10 
2017-10-30 19:55:20 ['this is an october tweet'] 
9 
2017-09-30 19:55:20 ['this is some tweet text'] 
2017-09-30 20:55:20 ['this is another tweet'] 
>>>  

当然,您可以以更好的格式打印它等等(需要内部连接,因为每个键似乎都是一个列表):

>>> for month, group in groupby(d.items(), lambda (k, v): k.month): 
...     tweets = list(group) 
...     print("%d tweet(s) in month %d" % (len(tweets), month)) 
...     print('\n'.join(','.join(tweet) for (dt, tweet) in tweets)) 
...      
1 tweet(s) in month 10 
this is an october tweet 
2 tweet(s) in month 9 
this is some tweet text 
this is another tweet 
>>>