2 回答
TA贡献2011条经验 获得超2个赞
根据 Alex 的回答,这里有一个稍微优化和改进的解决方案:
import datetime
HALFHOUR_RATE = 0.6
NIGHT_FEE = 5
def get_charge2(start_datetime, end_datetime):
tmp_datetime = start_datetime
charged = 0
while tmp_datetime < end_datetime:
if tmp_datetime.hour >= 7 and tmp_datetime.hour < 22 or (tmp_datetime.hour == 22 and tmp_datetime.minute < 30):
# It is a day [7, 22:30)
charged += HALFHOUR_RATE * 10 # avoid rounding error
tmp_datetime += datetime.timedelta(minutes=30)
else:
# It is a night [22:30, 7)
charged += NIGHT_FEE * 10 # avoid rounding error
tmp_datetime += datetime.timedelta(hours=8.5) # night == 8.5 hours
return charged/10 # adjust result
TA贡献1883条经验 获得超3个赞
最简单的方法是每 30 分钟迭代一次并以这种方式计算费用。
HALFHOUR_RATE = 0.6
NIGHT_FEE = 5
def get_charge(start_datetime, end_datetime):
tmp_datetime = start_datetime
charged = 0
last_night_charged_day = None
while tmp_datetime < end_datetime:
if tmp_datetime.hour >= 22 or tmp_datetime.hour < 7:
if tmp_datetime.hour == 22 and tmp_datetime.minute < 30:
# Still not a night
charged += HALFHOUR_RATE
# It is a night
else:
day = tmp_datetime.day
if tmp_datetime.hour < 7:
day -= 1
if day != last_night_charged_day:
last_night_charged_day = day
# Charge one time night fee
charged += NIGHT_FEE
else:
# It is a day
charged += HALFHOUR_RATE
tmp_datetime += datetime.timedelta(minutes=30)
return charged
添加回答
举报