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'
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.
Pandas DataFrame equals() MethodThe duplicated() method compares two DataFrames and returns True if they are equal, in both shape and content, otherwise False.
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.
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With