简体   繁体   English

如何根据python中的时间表验证给定的时间间隔?

[英]How to validate a given time interval against a time table in python?

I wrote some lines of code (python 3.7) to check for a given point in time, which timeslot in a time table it matches. 我编写了一些代码行(python 3.7)来检查给定的时间 ,它匹配时间表中的哪个时隙。 For this purpose I use pythons datetime module. 为此,我使用pythons datetime模块。 My problem is that I don't know how to check this for a period in time. 我的问题是我不知道如何在一段时间进行检查。 I ran through a lot of related subjects while searching for an answer, but I could not find anything that comes close enough. 在寻找答案时,我经历了很多相关主题,但是找不到足够接近的东西。

I got this working for a point in time (timestamp) 我在某个时间点 (时间戳记)上进行了此操作

pseudo code : 伪代码

time_point = 11:00
timeslot_1 = 10:00 - 12:00
timeslot_2 = 12:00 - 14:00

def check_interval(time_unit):
    if time_unit within timeslot_1:
      return timetable_interval_1
    if time_unit within timeslot_2:
      return timetable_interval_2
    else:
      return False

check_interval(time_point)

output: 输出:

10:00 - 12:00

But I would like to know this for a period in time (interval between two timestamps) 但我想知道一段时间 (两个时间戳记之间的间隔)

pseudo code : 伪代码

time_period = 11:00 - 12:30
timeslot_1 = 10:00 - 12:00
timeslot_2 = 12:00 - 14:00

def check_interval(time_unit):
    if time_unit within timeslot_1:
      return timeslot_1
    if time_unit within timeslot_2:
      return timeslot_2
    if time_unit within timeslot_1 and within timeslot_2:
      return timeslot_1 + timeslot_2
    else:
      return False

check_interval(time_period)

output 产量

10:00 - 14:00

You could use time to define time points, and tuples of times to represent intervals. 您可以使用time来定义时间点,并使用time元组来表示时间间隔。 For example: 例如:

from datetime import time

time_period = time(11), time(12, 30)
timeslot_1 = time(10), time(12)
timeslot_2 = time(12), time(14)

def check_interval(period):
    if timeslot_1[0] <= period[0] <= period[1] <= timeslot_1[1]:
      return timeslot_1
    if timeslot_2[0] <= period[0] <= period[1] <= timeslot_2[1]:
      return timeslot_2
    if timeslot_1[0] <= period[0] <= period[1] <= timeslot_2[1]:
      return timeslot_1[0], timeslot_2[1]
    else:
      return False

print(check_interval((time(11), time(12, 30))))
# prints (datetime.time(10, 0), datetime.time(14, 0))

print(check_interval((time(9), time(12, 30))))
# prints False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM