如何获得两个日期之间的特定月份和工作日数。
如果日期是
datetime.datetime(2004, 01, 01)
datetime.datetime(2005, 10, 01)
我希望我的输出为
{'January':2, 'February':2, ..., 'December':1}
{'Monday':xx, ..., 'Sunday':xx}
In 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}
As @thg435 correctly commented, dateutil
is not in standard Python library. It can be, however, replaced by the following command:
dtstart = datetime(2004, 01, 01)
until = datetime(2005, 10, 01)
rule = [dtstart + timedelta(i) for i in xrange((until - dtstart).days + 1)]