44
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのdatetimeで日付の範囲を比較演算子で指定する

Posted at

最近発見したんですが、Pythonの datetime オブジェクトは 比較演算子 が使えるようです。

from datetime import datetime

targets = [ # 6/1から6/30までのデータ
  datetime.datetime(2017, 6, 1, 0, 0),
  datetime.datetime(2017, 6, 2, 0, 0),
  datetime.datetime(2017, 6, 3, 0, 0),
  datetime.datetime(2017, 6, 4, 0, 0),
  datetime.datetime(2017, 6, 5, 0, 0),
  # (中略)
  datetime.datetime(2017, 6, 25, 0, 0),
  datetime.datetime(2017, 6, 26, 0, 0),
  datetime.datetime(2017, 6, 27, 0, 0),
  datetime.datetime(2017, 6, 28, 0, 0),
  datetime.datetime(2017, 6, 29, 0, 0),
  datetime.datetime(2017, 6, 30, 0, 0)
]

たとえば上記のような一ヶ月のデータが配列で渡されたとして、

from_dt = datetime(2017, 6, 10)
to_dt = datetime(2017, 6, 20)

取得したい日付の 開始日終了日datetime オブジェクトを作ります。
そして 開始日 <= 判定するdatetimeオブジェクト <= 終了日 という形で比較演算子を用います。

for target in targets:
  if from_dt <= target <= to_dt: # 6/20より小さく6/10よりも大きい
    print target

# 結果:
# 2017-06-10 00:00:00
# 2017-06-11 00:00:00
# 2017-06-12 00:00:00
# 2017-06-13 00:00:00
# 2017-06-14 00:00:00
# 2017-06-15 00:00:00
# 2017-06-16 00:00:00
# 2017-06-17 00:00:00
# 2017-06-18 00:00:00
# 2017-06-19 00:00:00
# 2017-06-20 00:00:00

これで開始日から終了日までのデータを取得することができました。割りと簡単ですね

44
29
0

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
44
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?