LoginSignup
47
30

More than 3 years have passed since last update.

【Python】指定した期間の連続した日付をだす

Last updated at Posted at 2018-09-04

分析的な業務をやっていると日付毎に集計したいというニーズがあるのですが、そのときに掲題の処理が必要になったのでメモ。

ほしい結果

2018-01-01
2018-01-02
2018-01-03
2018-01-04
2018-01-05
2018-01-06
2018-01-07
2018-01-08
2018-01-09
2018-01-10

こういうの。

コード


from datetime import datetime
from datetime import timedelta

start = datetime.strptime('2018-09-01', '%Y-%m-%d')
end   = datetime.strptime('2018-09-05', '%Y-%m-%d')

def daterange(_start, _end):
    for n in range((_end - _start).days):
        yield _start + timedelta(n)


for i in daterange(start, end):
    print (i)

結果

2018-09-01 00:00:00
2018-09-02 00:00:00
2018-09-03 00:00:00
2018-09-04 00:00:00

参考までに

start = datetime.strptime('2018-09-01', '%Y-%m-%d')
end   = datetime.strptime('2018-09-05', '%Y-%m-%d')

の部分を、

start = datetime.strptime('201801', '%Y%m')
end   = datetime.strptime('201802', '%Y%m')

というふうに変えると、

2018-01-01 00:00:00
2018-01-02 00:00:00
2018-01-03 00:00:00
2018-01-04 00:00:00
2018-01-05 00:00:00
2018-01-06 00:00:00
2018-01-07 00:00:00
2018-01-08 00:00:00
2018-01-09 00:00:00
2018-01-10 00:00:00
2018-01-11 00:00:00
2018-01-12 00:00:00
2018-01-13 00:00:00
2018-01-14 00:00:00
2018-01-15 00:00:00
2018-01-16 00:00:00
2018-01-17 00:00:00
2018-01-18 00:00:00
2018-01-19 00:00:00
2018-01-20 00:00:00
2018-01-21 00:00:00
2018-01-22 00:00:00
2018-01-23 00:00:00
2018-01-24 00:00:00
2018-01-25 00:00:00
2018-01-26 00:00:00
2018-01-27 00:00:00
2018-01-28 00:00:00
2018-01-29 00:00:00
2018-01-30 00:00:00
2018-01-31 00:00:00

という風にもだせます。幸せいっぱいです。

00:00:00

がいらない場合は、

start = datetime.strptime('201801', '%Y%m').date()
end = datetime.strptime('201802', '%Y%m').date()

とすれば大丈夫です。

47
30
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
30