我需要计算两个日期之间活动的确切秒数。但是,该事件可能有额外的限制 - 它可能只在某些时间段和/或一周中的几天内有效。
我尝试将 rrule 与频率一起使用rrule.SECONDLY
,但该函数需要 2-3 秒才能运行 - 而且此计算需要非常快速地运行,大约 3 毫秒。我使用rrule.HOURLY
并乘以3600。
我实现了一个如下所示的系统,但它的缺点是在示例中它不计算结束日期 16:00 小时后的 28 分钟和开始日期 16:00 小时后的 10 分钟。
例子:
from datetime import datetime
from dateutil import rrule
time_slot = {'start': "173000", 'end': "180000"}
start_date = datetime(2015, 3, 5, 16, 50)
end_date = datetime(2015, 3, 27, 16, 28)
start_hour = int(time_slot.get('start', '000000')[0:2])
end_hour = int(time_slot.get('end', '235959')[0:2])
start_minute = int(time_slot.get('start', '000000')[2:4])
end_minute = int(time_slot.get('end', '235959')[2:4])
time_slot_hours = []
time_slot_minutes = []
if start_minute:
time_slot_minutes.append({'hour': start_hour, 'minutes': [m for m in range(start_minute, 60)]})
start_hour += 1
if end_minute:
time_slot_minutes.append({'hour': end_hour, 'minutes': [m for m in range(0, end_minute)]})
for hour in range(start_hour, end_hour):
time_slot_hours.append(hour)
active_seconds = 60 * 60 * len(list(rrule.rrule(rrule.HOURLY, byhour=time_slot_hours, dtstart=start, until=end)))
for m in time_slot_minutes:
active_seconds += 60 * len(list(rrule.rrule(rrule.MINUTELY, byminute=m['minutes'], byhour=m['hour'], dtstart=start, until=end)))
有没有更优雅的方法来解决这个问题?