繁体   English   中英

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

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

我编写了一些代码行(python 3.7)来检查给定的时间 ,它匹配时间表中的哪个时隙。 为此,我使用pythons datetime模块。 我的问题是我不知道如何在一段时间进行检查。 在寻找答案时,我经历了很多相关主题,但是找不到足够接近的东西。

我在某个时间点 (时间戳记)上进行了此操作

:

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)

输出:

10:00 - 12:00

但我想知道一段时间 (两个时间戳记之间的间隔)

:

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)

产量

10:00 - 14:00

您可以使用time来定义时间点,并使用time元组来表示时间间隔。 例如:

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