Specify a date range with a comparison operator in Python's datetime

I recently discovered that Python's datetime object seems to be able to use the ** comparison operator **.

from datetime import datetime

targets = [ # 6/1 to 6/Data up to 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),
  #(Omitted)
  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)
]

For example, if the above one month data is passed as an array,

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

Create a datetime object with ** start date ** and ** end date ** for the dates you want to get. Then use a comparison operator in the form start date <= datetime object to determine <= end date.

for target in targets:
  if from_dt <= target <= to_dt: # 6/Less than 20 6/Greater than 10
    print target

#result:
# 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

Now you can get the data from the start date to the end date. It's relatively easy

Recommended Posts

Specify a date range with a comparison operator in Python's datetime
Use "$ in" operator with mongo-go-driver
Implement a date setter in Tkinter
Create a Kubernetes Operator in Python
Created a new corona app in Kyoto with Python's web framework Dash
Conversion of string <-> date (date, datetime) in Python
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Draw a heart in Ruby with PyCall
Create a GUI app with Python's Tkinter
Playing card class in Python (with comparison)
Dynamically specify a ModelChoiceField queryset in Django
Is Python's in operator slow? (From ABC167D)
Receive date type (datetime) with ArgumentParser [python]
Use Python3's Subprocess.run () in a CGI script