へっぽこびんぼう野郎のnewbie日記

けろけーろ(´・ω・`)! #vZkt8fc6J

python. ずらーっと並んでいる日付を、月ごとに見やすくまとめる方法

じみにべんり

In [60]: import datetime

In [61]: start = datetime.date(2015, 9, 23)

In [62]: [start + datetime.timedelta(days=n) for n in range(7)]
Out[62]:
[datetime.date(2015, 9, 23),
 datetime.date(2015, 9, 24),
 datetime.date(2015, 9, 25),
 datetime.date(2015, 9, 26),
 datetime.date(2015, 9, 27),
 datetime.date(2015, 9, 28),
 datetime.date(2015, 9, 29)]

In [69]: import itertools

In [71]: for x in itertools.groupby(enumerate(date_set), lambda x: x[1].day - x[0]):
        groups = [y for y in x[1]]
        print(groups[0][1], '~', groups[-1][1])
   ....:
2015-09-23 ~ 2015-09-29

In [72]: date_set = [start + datetime.timedelta(days=n) for n in range(400)]

In [73]: exec(_i71)
2015-09-23 ~ 2015-09-30
2015-10-01 ~ 2015-10-31
2015-11-01 ~ 2015-11-30
2015-12-01 ~ 2015-12-31
2016-01-01 ~ 2016-01-31
2016-02-01 ~ 2016-02-29
2016-03-01 ~ 2016-03-31
2016-04-01 ~ 2016-04-30
2016-05-01 ~ 2016-05-31
2016-06-01 ~ 2016-06-30
2016-07-01 ~ 2016-07-31
2016-08-01 ~ 2016-08-31
2016-09-01 ~ 2016-09-30
2016-10-01 ~ 2016-10-26

はてなブログシンタックスハイライトあったんだな(´・ω・`)