从日期列表中计算每个月的天数 python

Count of days of each month from a list of dates python

如何根据 python 中的日期列表计算当年每个月的天数。假设我有一个日期列表:

10/Mar/2016 06:39:31
16/Nov/2015 06:16:27
16/Dec/2012 06:39:31
16/Dec/2015 06:16:27
9/Mar/2016 06:16:27
15/Nov/2015 06:16:27
15/Mar/2012 06:39:31
15/Nov/2015 06:16:27
15/Sep/2015 06:16:27
15/Jan/2015 06:16:27
16/Feb/2016 06:16:27
16/Jan/2016 06:39:31
16/Feb/2016 06:39:31
15/Feb/2012 06:16:27
12/Mar/2016 06:16:27
16/Nov/2012 06:16:27
8/Jan/2016 06:16:27
10/Mar/2016 06:39:31
16/Nov/2012 06:39:31
16/Nov/2012 06:16:20
7/Mar/2016 06:16:27
15/Nov/2012 06:16:27
16/Jan/2016 06:16:27
16/Oct/2015 06:39:31

现在我想要Jan-3Feb-2Mar-5等等。

我试过了

from datetime import datetime as date_for_conv
if(times> date_for_conv.strptime(times, "%d/%b/%Y %H:%M:%S").strftime("2016/Jan/%d")):
    jan+=1

times是循环迭代的列表元素。这只给出了 1 月的计数,我想在一次条件检查中完成。我该怎么办?

假设您的数据在 data.txt 中,这是一种相当有效的方式(无需将所有内容读入内存并对其进行排序)。我最近对 ​​itertools 和集合有点着迷,主要是因为它们往往使事情变得更快,但它也更像 pythonic。查阅有关它们如何工作的文档留作 reader.

的练习。
from itertools import imap
from collections import defaultdict

counters = defaultdict(int)
with open('data.txt', 'r') as fp:
    lines = iter(fp.readline, '')
    mos = imap(lambda s: s.split('/')[1], lines)
    for mo in mos:
        counters[mo] += 1

for m, c in counters.items():
    print "{}: {}".format(m, c)

编辑:我知道你也有这样的要求,如果一个月没有日期,那么你也想要列出那些。为此,您可以导入 calendar 模块,但您将 运行 陷入语言环境问题。所以最好简单地遍历所有 12 个月:

for m in ('Jan', 'Feb', ...):
    print "{}: {}".format(m, counters.get(m, 0))

一个简单的计数方法是使用字典。添加新密钥并递增(如果存在):

from datetime import datetime
times = ['10/Mar/2016 06:39:31','16/Nov/2015 06:16:27','16/Dec/2012 06:39:31','16/Dec/2015 06:16:27',
         '9/Mar/2016 06:16:27','15/Nov/2015 06:16:27','15/Mar/2012 06:39:31','15/Nov/2015 06:16:27',
         '15/Sep/2015 06:16:27','15/Jan/2015 06:16:27','16/Feb/2016 06:16:27','16/Jan/2016 06:39:31',
         '16/Feb/2016 06:39:31','15/Feb/2012 06:16:27','12/Mar/2016 06:16:27','16/Nov/2012 06:16:27',
         '8/Jan/2016 06:16:27','10/Mar/2016 06:39:31','16/Nov/2012 06:39:31','16/Nov/2012 06:16:20',
         '7/Mar/2016 06:16:27','15/Nov/2012 06:16:27','16/Jan/2016 06:16:27','16/Oct/2015 06:39:31']

counters = {}
for t in times:
    month = datetime.strptime(t, "%d/%b/%Y %H:%M:%S").strftime('%b')
    if month in counters:
        counters[month] += 1
    else:
        counters[month] = 1

for k,v in counters.items():
    print('{}-{}'.format(k,v))

这个returns:

Oct-1
Dec-2
Mar-6
Jan-4
Feb-3
Sep-1
Nov-7