def to_python(self): question = self.get_question() if 'timezone' in question: tzinfo = pytz.timezone(question['timezone']) else: tzinfo = pytz.timezone(get_localzone_name()) from_date = None to_date = None value = self.get_value() from_value = value.get('from') if from_value: year, month, day = from_value.split('-') from_date = tzinfo.localize( datetime(int(year), int(month), int(day)), ) to_value = value.get('to') if to_value: year, month, day = to_value.split('-') to_date = tzinfo.localize(datetime(int(year), int(month), int(day))) return { 'from': from_date, 'to': to_date, }
async def __async_get_bridge_config(self, full_details: bool = False) -> dict: """Return the (virtual) bridge configuration.""" result = self.hue.config.definitions.get("bridge").get("basic").copy() result.update({ "name": self.config.bridge_name, "mac": self.config.mac_addr, "bridgeid": self.config.bridge_id, }) if full_details: result.update( self.hue.config.definitions.get("bridge").get("full")) result.update({ "linkbutton": self.config.link_mode_enabled, "ipaddress": self.config.ip_addr, "gateway": self.config.ip_addr, "UTC": datetime.datetime.utcnow().isoformat().split(".")[0], "localtime": datetime.datetime.now().isoformat().split(".")[0], "timezone": self.config.get_storage_value("bridge_config", "timezone", tzlocal.get_localzone_name()), "whitelist": await self.__async_whitelist_to_bridge_config(), "zigbeechannel": self.config.get_storage_value("bridge_config", "zigbeechannel", 25), }) return result
def __init__(self, config_file_path=None): # catch SIGINT, SIGQUIT and SIGTERM self.__quit_signal = threading.Event() signal.signal(signal.SIGINT, self.__quit) signal.signal(signal.SIGQUIT, self.__quit) signal.signal(signal.SIGTERM, self.__quit) # catch SIGHUP and reload configuration signal.signal(signal.SIGHUP, self.__reload) # load config if config_file_path is None: self.__config_file_path = DEFAULT_CONFIG_FILE else: self.__config_file_path = config_file_path self.__load_settings() # this is the queue that holds the frames to display self.__frame_queue = queue.Queue(maxsize=1) # animation controller # gets initialized in mainloop method self.__animation_controller = AnimationController( self.config, self.frame_queue) # the animation scheduler self.__animation_scheduler = self.__create_scheduler() self.__schedule_lock = Lock() # the nighttime scheduler self.__location = lookup(tzlocal.get_localzone_name().split("/")[1], database()) self.__nighttime_scheduler = BackgroundScheduler() self.__sunrise_job = self.__nighttime_scheduler.add_job( func=self.apply_brightness) self.__sunset_job = self.__nighttime_scheduler.add_job( func=self.apply_brightness) self.__nighttime_scheduler.add_job(func=self.__calculate_nighttimes, trigger=CronTrigger(hour="0,12", minute=0, second=0)) self.__calculate_nighttimes() self.apply_brightness() self.__nighttime_scheduler.start() # create the display object self.__initialize_display() # server interfaces self.__http_server = None self.__rest_server = None self.__tpm2_net_server = None # this signal is set by the reload method self.__reload_signal = EventWithUnsetSignal()
def set_brightness(): """Set the Unicorn hat's brightness according to the current sunrise/sunset time""" now = datetime.datetime.now() latitude, longitude = get_current_location() loc = LocationInfo(latitude=latitude, longitude=longitude) sunInfo = sun.sun(loc.observer, date=now.date(), tzinfo=get_localzone_name()) utcNow = datetime.datetime.now(datetime.timezone.utc) if utcNow < sunInfo["sunrise"] or utcNow > sunInfo["sunset"]: unicorn.brightness(0.10) else: unicorn.brightness(0.75)
def to_python(self): value = self.get_value() if not value: return question = self.get_question() if 'timezone' in question: tzinfo = pytz.timezone(question['timezone']) else: tzinfo = pytz.timezone(get_localzone_name()) year, month, day = value.split('-') return tzinfo.localize(datetime(int(year), int(month), int(day)), )
def detect_tz() -> str: iana_key = tzlocal.get_localzone_name() if iana_key is None: raise cv.Invalid( "Could not automatically determine timezone, please set timezone manually." ) _LOGGER.info("Detected timezone '%s'", iana_key) tzfile = _load_tzdata(iana_key) if tzfile is None: raise cv.Invalid( "Could not automatically determine timezone, please set timezone manually." ) ret = _extract_tz_string(tzfile) _LOGGER.debug(" -> TZ string %s", ret) return ret
def get_system_zone() -> str: try: import tzlocal # note: tzlocal mypy stubs aren't aware of api change yet (see https://github.com/python/typeshed/issues/6038) try: # 4.0 way return tzlocal.get_localzone_name() # type: ignore[attr-defined] except AttributeError as e: # 2.0 way zone = tzlocal.get_localzone().zone # type: ignore[attr-defined] # see https://github.com/python/typeshed/blame/968fd6d01d23470e0c8368e7ee7c43f54aaedc0e/stubs/pytz/pytz/tzinfo.pyi#L6 # it says all concrete instances should not be None assert zone is not None return zone except Exception as e: logger.exception(e) logger.error("Couldn't determine system timezone. Falling back to UTC. Please report this as a bug!") return 'UTC'
def client_info_table(): t = { 'name': CLIENT_INFO_TABLE_NAME, 'desc': 'The client info.', 'columns': [ pk(), Column('hostname', String(128), default=get_hostname(), unique=True, sqlite_on_conflict_unique='REPLACE', comment='The client hostname.'), Column('tz', TimezoneType(backend='pytz'), default=tzlocal.get_localzone_name(), comment='The client time zone.'), created_at(), updated_at(), ] } return t
class StandardMetadataFilter(logging.Filter): """ Filter that adds few more attributes to log records. +-------------------+----------------------------------------------+ | placeholder | description | +-------------------+----------------------------------------------+ | %(hostname)s | hostname | +-------------------+----------------------------------------------+ | %(isotime)s | Local time represented as ISO8601 | +-------------------+----------------------------------------------+ | %(isotime_utc)s | local time converted to UTC and represented | | | as ISO8601 string | +-------------------+----------------------------------------------+ """ try: _HOSTNAME = socket.gethostname() except Exception as exception: _HOSTNAME = "-" _LOCAL_TZ = ZoneInfo(tzlocal.get_localzone_name()) def filter(self, record): # Note that naive datetime will not be exported correctly to isoformat: # datetime.now().isoformat() # '2017-05-22T13:51:49.336335' # but we don't have this problem because we make sure that here we # always have tzinfo on datetime object dt = datetime.fromtimestamp( record.created).replace(tzinfo=self._LOCAL_TZ) record.isotime = dt.isoformat() record.isotime_utc = dt.astimezone(ZoneInfo("UTC")).isoformat() record.hostname = self._HOSTNAME return super().filter(record)
"font.family": "微软雅黑", "font.size": 12, "log.active": True, "log.level": CRITICAL, "log.console": True, "log.file": True, "email.server": "smtp.qq.com", "email.port": 465, "email.username": "", "email.password": "", "email.sender": "", "email.receiver": "", "datafeed.name": "", "datafeed.username": "", "datafeed.password": "", "database.timezone": get_localzone_name(), "database.name": "sqlite", "database.database": "database.db", "database.host": "", "database.port": 0, "database.user": "", "database.password": "" } # Load global setting from json file. SETTING_FILENAME: str = "vt_setting.json" SETTINGS.update(load_json(SETTING_FILENAME)) def get_settings(prefix: str = "") -> Dict[str, Any]: prefix_length: int = len(prefix)
def get_localzone_name_compat(): try: return get_localzone_name() except Exception: return None