关于datetime:在python中的两个日期之间计算9:00 PM

Calculate 9:00 PM in between two dates in python

我如何计算在两个日期之间可以有多少次晚上9:00?

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

预期输出为1

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

预期输出1

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

预期产量2


您可以通过将两个日期之间的时间差转换为天来完成此操作,并在日期范围因往返而错过额外的9点时添加一天。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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