Functional approach without third-party requirements. Just the stdlib.
By the way, Python has also the module sched, but the implementation and API aren't the best.
Added unnecessary TypeHints, but it helps your IDE to detect human errors.
By the way, Python has also the module sched, but the implementation and API aren't the best.
Added unnecessary TypeHints, but it helps your IDE to detect human errors.
Code:
import datetimefrom typing import Callabledef is_between( start: datetime.time, end: datetime.time) -> Callable[[datetime.time], bool]: """ This function returns a function, which checks, if clock is between start and end. """ def inner(clock: datetime.time): """ Compare with actual time """ return ( # the special case, time is crossing 0:00 start > end and datetime.time(0) <= clock <= start and clock <= end # the normal case, not crossing 0:00 or start <= clock <= end ) return innerdef main(): # calling the closure (function), which returns a prepared function, # which takes datetime.time as argument between = is_between(datetime.time(1, 0), datetime.time(13, 00)) # shortcut to create datetime.time instances T = datetime.time # if you're dealing with datetime.datetime objects, # the method time() on this instances return a datetime.time obect, # dateime.time, datetime.date, datetime.datetime and datetime.timedelta # can be compared # testcode for t in (T(0, 30), T(13), T(14), T(0), T(16), T(17), T(3)): # calling the prepared function with t, which are datetime.time instances if between(t): print("Clock:", t, "is between 1:00 and 13:00") else: print("Clock:", t, "is NOT between 1:00 and 13:00")main()
Statistics: Posted by DeaD_EyE — Wed Dec 25, 2024 3:02 pm