-2

How can I calculate how many times 9:00 PM can come in between two dates?

dt_start_time = "2014-09-23 11:00:00"
dt_end_time   = "2014-09-24 12:00:00"

Expected Output is 1

dt_start_time = "2014-09-24 09:00:00"
dt_end_time   = "2014-09-24 22:00:00"

Expected Output 1

dt_start_time = "2014-09-24 09:00:00"
dt_end_time   = "2014-09-26 12:00:00"

Expected Output 2

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Anurag
  • 1,013
  • 11
  • 30

1 Answers1

1

You can do this simply by converting the time difference between the two dates to days, and add an extra day if the dates range misses an extra 9 PM because of roundoff

dt_start_time = "2014-09-23 11:00:00"
dt_end_time = "2014-09-24 23:00:00"

format = "%Y-%m-%d %H:%M:%S"

from datetime import datetime as dt

st = dt.strptime(dt_start_time, format)
end = dt.strptime(dt_end_time, format)

count = (end - st).days
if st.hour < 21 and end.hour >= 21:
    count += 1
print count
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • @Anurag Your expected output for 2nd casse is wrong, how can you have 9PM between 9AM and 12 noon on same day? The result should be 0, and that is what I output.. – Anshul Goyal Sep 25 '14 at 06:46
  • Agree, second case is wrong. Have updated, Thanks :-) – Anurag Sep 25 '14 at 07:04