Pythonで2つのdatetimeオブジェクトの期間の1日ごとに処理をする
2つのdatetimeオブジェクトがあって、その期間の1日ごとに処理を行いたいケースがあったので、調べたところ以下のような感じに落ち着いた
from datetime import datetime, timedelta start = datetime.strptime('201201', '%Y%m') end = datetime.strptime('201202', '%Y%m') def daterange(start_date, end_date): for n in range((end_date - start_date).days): yield start_date + timedelta(n) for i in daterange(start, end): # 処理 print i # => 2012-01-01 00:00:00 # => 2012-01-02 00:00:00 # => 2012-01-03 00:00:00 # => 2012-01-04 00:00:00 # => 2012-01-05 00:00:00 # => 2012-01-06 00:00:00 # => 2012-01-07 00:00:00 # => 2012-01-08 00:00:00 # => 2012-01-09 00:00:00 # => 2012-01-10 00:00:00 # => 2012-01-11 00:00:00 # => 2012-01-12 00:00:00 # => 2012-01-13 00:00:00 # => 2012-01-14 00:00:00 # => 2012-01-15 00:00:00 # => 2012-01-16 00:00:00 # => 2012-01-17 00:00:00 # => 2012-01-18 00:00:00 # => 2012-01-19 00:00:00 # => 2012-01-20 00:00:00 # => 2012-01-21 00:00:00 # => 2012-01-22 00:00:00 # => 2012-01-23 00:00:00 # => 2012-01-24 00:00:00 # => 2012-01-25 00:00:00 # => 2012-01-26 00:00:00 # => 2012-01-27 00:00:00 # => 2012-01-28 00:00:00 # => 2012-01-29 00:00:00 # => 2012-01-30 00:00:00 # => 2012-01-31 00:00:00
参考)
http://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python