簡體   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