如何计算一个日期范围内的秒数,只计算特定的小时和/或天?

2024-04-16 17:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算两个日期之间活动的确切秒数。但是,事件可能有其他限制-它可能仅在一周中的某些时段和/或几天处于活动状态。你知道吗

我尝试使用频率为rrule.SECONDLY的rrule,但是函数需要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)))

有没有更优雅的方法来解决这个问题?你知道吗


Tags: inforgetdatetimetimestartintend