once a night Boolean gate

fukurou

the supreme coder
ADMIN
Python:
import time
from datetime import datetime

class NightOnceGate:
    def __init__(self, night_start_hour=21, night_end_hour=6):
        """
        night_start_hour: hour (0-23) night begins, e.g. 21 = 9pm
        night_end_hour: hour (0-23) night ends, e.g. 6 = 6am
        Handles wraparound past midnight.
        """
        self.night_start_hour = night_start_hour
        self.night_end_hour = night_end_hour
        self.last_fired_date = None  # tracks the calendar date it last returned True

    def is_night(self, now=None):
        now = now or datetime.now()
        h = now.hour
        if self.night_start_hour > self.night_end_hour:
            # wraps past midnight, e.g. 21 -> 6
            return h >= self.night_start_hour or h < self.night_end_hour
        else:
            return self.night_start_hour <= h < self.night_end_hour

    def check(self, now=None):
        now = now or datetime.now()
        today = now.date()

        if self.last_fired_date == today:
            return False  # already fired today

        if not self.is_night(now):
            return False  # not nighttime yet

        self.last_fired_date = today
        return True
 
Top