Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if time is between tonight and tomorrow morning

The following condition does not work, any idea? Does Python think that 8am belongs to the same day and so this condition is not possible?

from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(23,00) and now_time <= time(8,00): 
    try:
        print 'hall light turning on'
    except:
        print 'Could not connect to Hue gateway'
like image 355
Ossama Avatar asked Dec 19 '13 20:12

Ossama


People also ask

How do you check if a time is between two times in python?

Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.

How do you know if two dates are equal in pandas?

Pandas DataFrame equals() MethodThe duplicated() method compares two DataFrames and returns True if they are equal, in both shape and content, otherwise False.

How do you check if a date is weekday in Python?

Check if a date is a weekday or weekend We can use the weekday() method of a datetime. date object to determine if the given date is a weekday or weekend. Note: The weekday() method returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, the date(2022, 05, 02) is a Monday.


2 Answers

How could the hour be simultaneously >= 23 and <= 8?

Try replacing and with or:

if now_time >= time(23,00) or now_time <= time(8,00):
    print "night"
like image 183
Mark Ransom Avatar answered Sep 19 '22 12:09

Mark Ransom


Astral is a module that can give you a more accurate indication of "night time" based on the sun's current location. It's good when you want to automate turning lights on or off more efficiently by using dawn to dusk or sunset to sunrise and indicating what city you're in. Check out: https://astral.readthedocs.io/en/latest/

Sample Usage:

import pytz
from datetime import datetime
from astral import Astral
a = Astral()
city = a['Chicago'] # Replace with your city
now = datetime.now(pytz.utc)
sun = city.sun(date=now, local=True)
if now >= sun['dusk'] or now <= sun['dawn']:
    print "It's dark outside"
like image 28
Kenny Ingle Avatar answered Sep 19 '22 12:09

Kenny Ingle