1

I want to generate a list of the dates in yyyy-mm-dd format for every Monday and Saturday in a given year using Python's calendar module (or something else if it's a better fit, but I'd prefer not to have to bring in an outside library).

However, functions that give you data for the entire year like calendar.calendar() just output a calendar in string format, which, needless to say, would be unreasonably burdensome to work with.

What I want is something like calendar.monthcalendar, which returns a matrix with 7 entries for each list, each representing an ordered day of the week. This, however, is also burdensome for my Monday and Saturday problem, because some weeks span 2 months (i.e., end and beginning of the month).

I suppose I could develop an awkward hack to work through that, but I'm hoping there is a better way I'm overlooking.

2 Answers 2

5

IIUC, you can simply use datetime:

>>> year = 2013
>>> days = [datetime.datetime(year, 1, 1) + datetime.timedelta(days=i) for i in range(366)]
>>> days = [day for day in days if day.year == year and day.weekday() in (0, 5)]
>>> formatted = [day.strftime("%Y-%m-%d") for day in days]
>>> len(formatted)
104
>>> formatted[:10]
['2013-01-05', '2013-01-07', '2013-01-12', '2013-01-14', '2013-01-19', '2013-01-21', '2013-01-26', '2013-01-28', '2013-02-02', '2013-02-04']
2

Although it's a external dependency, dateutil has exactly the functionality you search via it rrule module.

>>> import datetime
>>> import dateutil.rrule as rr
>>> year = 2013
>>> mondays_saturdays = rr.rrule(rr.DAILY,
...                              dtstart=datetime.datetime(year, 1, 1),
...                              until=datetime.datetime(year, 12, 31),
...                              byweekday=(rr.MO, rr.SA)
... )
>>> print len(list(mondays_saturdays))
104
>>> print list(mondays_saturdays)[:5]
[datetime.datetime(2013, 1, 5, 0, 0), datetime.datetime(2013, 1, 7, 0, 0), datetime.datetime(2013, 1, 12, 0, 0), datetime.datetime(2013, 1, 14, 0, 0), datetime.datetime(2013, 1, 19, 0, 0)]
>>> 
1
  • +1: this is the right approach if the OP can use external modules.
    – DSM
    Jan 12, 2013 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.