How to check for a "between 23:00 and 6:30" condition?

148 Views Asked by At

I would like to check with arrow(*) whether the current time is between 23:00 and 6:30.

I currently use naive checks in the code below but was wondering whether there is an arrow native construction available

import arrow

def check(now):
    if now.hour >= 23 or now.hour < 6 or (now.hour == 6 and now.minute <= 30):
        print("we are between 23:00 and 6:30 the next day")
    else:
        print("we are outside the range")

#out
now = arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)

# in
now = arrow.get('2013-05-05 23:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)

# in
now = arrow.get('2013-05-06 01:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)

# in
now = arrow.get('2013-05-06 05:45:45', 'YYYY-MM-DD HH:mm:ss')
check(now)

# out
now = arrow.get('2013-05-06 07:30:45', 'YYYY-MM-DD HH:mm:ss')
check(now)

(*) I happily use arrow for years but if the solution is more straightforward with another package (dolorean or another one similar I forgot the name of) it is fine as well

1

There are 1 best solutions below

1
On

You can go with a default datetime python's library, but please keep in mind that you have to stick with a timezone, I would recommend using UTC by calling datetime.utcnow or datetime.now if you need local time. Here is an example:

In [12]: from datetime import datetime
In [13]: now = datetime.utcnow()
In [14]: now.hour
Out[14]: 16
In [15]: 6 < now.hour < 23
Out[15]: True

PS. If datetime is not an option by some reason, you can go with arrow.utcnow() or same localized arrow.now() variant.