How to find number of whole weeks between dates?

Ian Kelly ian.g.kelly at gmail.com
Wed Jun 10 23:35:53 EDT 2015


On Wed, Jun 10, 2015 at 8:01 PM, Sebastian M Cheung via Python-list
<python-list at python.org> wrote:
> yes just whole weeks given any two months, I did looked into calendar module but couldn't find specifically what i need.

>>> cal.monthdays2calendar(2014, 4) + cal.monthdays2calendar(2014, 5)
[[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)], [(7, 0),
(8, 1), (9, 2), (10, 3), (11, 4), (12, 5), (13, 6)], [(14, 0), (15,
1), (16, 2), (17, 3), (18, 4), (19, 5), (20, 6)], [(21, 0), (22, 1),
(23, 2), (24, 3), (25, 4), (26, 5), (27, 6)], [(28, 0), (29, 1), (30,
2), (0, 3), (0, 4), (0, 5), (0, 6)], [(0, 0), (0, 1), (0, 2), (1, 3),
(2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10,
5), (11, 6)], [(12, 0), (13, 1), (14, 2), (15, 3), (16, 4), (17, 5),
(18, 6)], [(19, 0), (20, 1), (21, 2), (22, 3), (23, 4), (24, 5), (25,
6)], [(26, 0), (27, 1), (28, 2), (29, 3), (30, 4), (31, 5), (0, 6)]]

You just need to:

1) Trim the first and last weeks off since they contain invalid dates.
2) Merge the overlapping last week of April and first week of May.
3) Count the resulting number of weeks in the list.

Alternatively, the dateutil.rrule module could probably be used to do
this fairly easily, but it's a third-party module and not part of the
standard library.

https://labix.org/python-dateutil



More information about the Python-list mailing list