from datetime import date, time, datetime, timedelta
def slice_datetimes_interval(start, end):
"""
Slices the interval between the datetimes start and end.
If start and end are on different days:
start time -> midnight | number of full days | midnight -> end time
---------------------- ------------------- --------------------
^ ^ ^
day_part_1 full_days day_part_2
If start and end are on the same day:
start time -> end time
----------------------
^
day_part_1 full_days = 0
Returns full_days and the list of day_parts (as tuples of time objects).
"""
if start > end:
raise ValueError("Start time must be before end time")
# Number of full days between the end of start day and the beginning of end day
# If start and end are on the same day, it will be -1
full_days = (datetime.combine(end, time.min) -
datetime.combine(start, time.max)).days
if full_days >= 0:
day_parts = [(start.time(), time.max),
(time.min, end.time())]
else:
full_days = 0
day_parts = [(start.time(), end.time())]
return full_days, day_parts
这里有一个解决方案。在
它做了两件事,首先它计算两个日期之间的完整天数,并且由于我们知道(我们可以近似地)每天是24小时,所以加权“白天”和“晚上时间”(计算以小时为单位)就相当简单了。所以现在我们只需要计算出剩下的不到24小时的间隔。这里的诀窍是“折叠”时间,这样“黎明”就不在一天的中间,而在0时,我们只有一个分隔符来表示“黄昏”,所以我们只有三种情况,都是白天时间,都是夜间,或者晚些的日期是夜间,较早的是白天。在
根据评论更新。在
一百万次函数调用的运行时间是在我的笔记本上
4.588s
。在一种解决方案,允许您定义任意多个周期,以及它们各自的权重。在
首先,一个helper函数将日期时间间隔切片:
计算给定期间和权重列表的加权持续时间的类:
^{pr2}$我们创建一个WeightedDuration实例,定义我们的周期及其权重。 我们可以有任意多个周期,权重小于或大于1。在
让我们计算日期时间之间的加权持续时间:
此解决方案计算完整日期的加权数,然后从第一个日期和最后一个日期中减去或添加任何残差。这并不能解释夏令时的影响。在
这在加权秒数内提供了解决方案,但您可以在之后转换为任何方便的方法
^{pr2}$相关问题 更多 >
编程相关推荐