两个日期之间特定月份/工作日的数量

时间:2012-05-11 08:45:32

标签: python datetime time

如何获得两个日期之间特定月份和工作日的数量。

如果日期是

datetime.datetime(2004, 01, 01)
datetime.datetime(2005, 10, 01)

我希望输出为

{'January':2, 'February':2, ..., 'December':1}
{'Monday':xx, ..., 'Sunday':xx}

1 个答案:

答案 0 :(得分:5)

在Python 2.7中:

from datetime import datetime
from dateutil import rrule
import itertools as it
from collections import Counter

rule = rrule.rrule(rrule.DAILY,
                   dtstart=datetime(2004, 01, 01),
                   until=datetime(2005, 10, 01))

dict(Counter(d.strftime('%A') for d in rule))
# {'Friday': 92,
#  'Monday': 91,
#  'Saturday': 92,
#  'Sunday': 91,
#  'Thursday': 92,
#  'Tuesday': 91,
#  'Wednesday': 91}

dict(Counter(k for k,v in it.groupby(d.strftime('%B') for d in rule)))
# or
dict(Counter(k for k,v in it.groupby(rule, key=lambda x: x.strftime('%B'))))

# {'April': 2,
#  'August': 2,
#  'December': 1,
#  'February': 2,
#  'January': 2,
#  'July': 2,
#  'June': 2,
#  'March': 2,
#  'May': 2,
#  'November': 1,
#  'October': 2,
#  'September': 2}

正如@ thg435正确评论的那样,dateutil不在标准Python库中。但是,它可以替换为以下命令:

dtstart = datetime(2004, 01, 01)
until = datetime(2005, 10, 01)
rule = [dtstart + timedelta(i) for i in xrange((until - dtstart).days + 1)]