python-3.xdatetimependulum

How to check if time is between two time intervals


I'm currently trying to figure out how I can make a duration between 1 AM to 7 AM (01:00-07:00) using Pendulum - I have been trying to read the documentation and the closests thing I could find was using duration however I was not able to see how I can check if the time is between 01:00 to 07:00.

I wonder if it is possible to use pendulum to check if the time is between the interval?

Expect:

Print out "The time is between 01:00 to 07:00" and if its not then print "The time is NOT between 01:00 to 07:00"


Solution

  • If I'm understanding you correctly, you're looking to determine if a given time is between 01:00 and 07:00. To be honest, you could getaway with just using datetime rather than installing a new package. With datetime, I would just do:

    import datetime
    curr_time = datetime.datetime.now()  # replace this line with whatever time or how you get your time
    if curr_time.hour >= 1 and curr_time.hour < 7:
        print("The time is between 01:00 to 07:00")
    else:
        print("The time is NOT between 01:00 and 07:00")
    

    Since pendulum inherits from datetime anyway, this should be compatible if you really want to use pendulum. You'll just need to change some syntax.