如何计算两个日期之间晚上9点的次数?
dt_start_time = "2014-09-23 11:00:00"
dt_end_time = "2014-09-24 12:00:00"
预期输出为1
dt_start_time = "2014-09-24 09:00:00"
dt_end_time = "2014-09-24 22:00:00"
预期产出1
dt_start_time = "2014-09-24 09:00:00"
dt_end_time = "2014-09-26 12:00:00"
预期产出2
答案 0 :(得分:1)
您可以通过将两个日期之间的时差转换为天数来实现此目的,如果日期范围因为收尾而错过额外的9点,则可以额外增加一天
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