def _ws_stream_get_events( msg_id: int, start_day: dt, end_day: dt, formatter: Callable[[int, Any], dict[str, Any]], event_processor: EventProcessor, partial: bool, ) -> tuple[str, dt | None]: """Fetch events and convert them to json in the executor.""" events = event_processor.get_events(start_day, end_day) last_time = None if events: last_time = dt_util.utc_from_timestamp(events[-1]["when"]) message = { "events": events, "start_time": dt_util.utc_to_timestamp(start_day), "end_time": dt_util.utc_to_timestamp(end_day), } if partial: # This is a hint to consumers of the api that # we are about to send a another block of historical # data in case the UI needs to show that historical # data is still loading in the future message["partial"] = True return JSON_DUMP(formatter(msg_id, message)), last_time
def _generate_stream_message(events: list[dict[str, Any]], start_day: dt, end_day: dt) -> dict[str, Any]: """Generate a logbook stream message response.""" return { "events": events, "start_time": dt_util.utc_to_timestamp(start_day), "end_time": dt_util.utc_to_timestamp(end_day), }
def async_fire_time_changed(hass: HomeAssistant, datetime_: datetime = None, fire_all: bool = False) -> None: """Fire a time changed event.""" if datetime_ is None: utc_datetime = date_util.utcnow() else: utc_datetime = date_util.as_utc(datetime_) timestamp = date_util.utc_to_timestamp(utc_datetime) for task in list(hass.loop._scheduled): if not isinstance(task, asyncio.TimerHandle): continue if task.cancelled(): continue mock_seconds_into_future = timestamp - time.time() future_seconds = task.when() - hass.loop.time() if fire_all or mock_seconds_into_future >= future_seconds: with patch( "homeassistant.helpers.event.time_tracker_utcnow", return_value=utc_datetime, ), patch( "homeassistant.helpers.event.time_tracker_timestamp", return_value=timestamp, ): task._run() task.cancel()
def process_datetime_to_timestamp(ts: datetime) -> float: """Process a datebase datetime to epoch. Mirrors the behavior of process_timestamp_to_utc_isoformat except it returns the epoch time. """ if ts.tzinfo is None or ts.tzinfo == dt_util.UTC: return dt_util.utc_to_timestamp(ts) return ts.timestamp()
def test_timestamp_to_utc(): """Test we can convert a utc datetime to a timestamp.""" utc_now = dt_util.utcnow() assert dt_util.utc_to_timestamp(utc_now) == utc_now.timestamp()