如何从 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-3
,Feb-2
,Mar-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月份的计数,我想在一次条件检查中完成。我该怎么办?
答案 0 :(得分:0)
假设您的数据位于data.txt中,这会以相当有效的方式完成(无需将所有内容读入内存并对其进行排序)。我最近对itertools和collection有点着迷,主要是因为它们往往会让事情变得更快,但它也更加pythonic。咨询有关其工作方式的文档是留给读者的练习。
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))
答案 1 :(得分: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))
返回:
Oct-1
Dec-2
Mar-6
Jan-4
Feb-3
Sep-1
Nov-7