def atafter(self, data: Union[str, datetime, date, time]): ''' Datetime/date/time at-or-after comparison ''' if isinstance(data, str): if isinstance(self.value) == datetime: data = datetime.fromisoformat(data) elif isinstance(self.value) == date: data = date.fromisoformat(data) elif isinstance(self.value) == time: data = time.fromisoformat(data) else: raise ValueError(f'Unexpected type of operator: {self.value}') if type(data) not in (datetime, date, time): raise ValueError( f'Data {data} is not of type datetime, date or time' ) return data >= self.value
def loadStartEndBreakDict(self, sebDict): for key in sebDict: # convert the values in the sebDict to datetime objects based on the date of the log #if sebDict[key] == '': # catch empty breaks try: sebDict[key] = datetime.combine( self.logDate, time.fromisoformat(sebDict[key])) except: print("Break not properly formatted") self.startTime = sebDict['callStart'] self.endTime = sebDict['callEnd'] break1 = Timeframe(sebDict["b1start"], sebDict["b1end"]) if break1.duration.total_seconds() > 0: self.breaks.append(break1) break2 = Timeframe(sebDict["b2start"], sebDict["b2end"]) if break1.duration.total_seconds() > 0: self.breaks.append(break2) break3 = Timeframe(sebDict["b3start"], sebDict["b3end"]) if break1.duration.total_seconds() > 0: self.breaks.append(break3)
async def apod_task(): await bot.wait_until_ready() morningTime = time.fromisoformat('08:00') channel = bot.get_channel(518253505669103617) # channel ID while not bot.is_closed(): now = datetime.now() if (now.hour == morningTime.hour): apodData = Apod.getApodData() if (apodData['media_type'] == 'image'): #gets image from a URL async with aiohttp.ClientSession() as session: async with session.get(apodData['url']) as resp: if resp.status != 200: return await channel.send( 'Could not download file...') data = io.BytesIO( await resp.read()) #create BytesIO instance await channel.send(":rocket:" + "\t" + "__**" + apodData['title'] + "**__" + "\t" + ":rocket:" + "\t" + "__**" + apodData['date'] + "**__" + "\t" + ":rocket:" + "\n") await channel.send(file=discord.File(data, 'apod.png')) await channel.send("```" + "\n" + apodData['explanation'] + "\n" + "```") elif (apodData['media_type'] == 'video'): await channel.send(":rocket:" + "\t" + "__**" + apodData['title'] + "**__" + "\t" + ":rocket:" + "\t" + "__**" + apodData['date'] + "**__" + "\t" + ":rocket:" + "\n") await channel.send(apodData['url'].replace( "?rel=0", "").replace("embed/", "watch?v=") + "\n") await channel.send("```" + "\n" + apodData['explanation'] + "\n" + "```") await asyncio.sleep(1 * (60 * 60)) # task to run once hourly
def typed_value(typeuri, val): # {"duration", ColTypeDuration}, if typeuri in ('boolean'): return np.bool, 'true' == val elif typeuri in ('byte'): return np.byte, np.int8(val) elif typeuri in ('short'): return np.short, np.short(val) elif typeuri in ('integer', 'int', 'nonNegativeInteger'): return np.intc, np.int(val) elif typeuri in ('long'): return np.int_, np.int_(val) elif typeuri in ('float'): return np.single, np.float32(val) elif typeuri in ('double', 'decimal'): return np.double, np.float64(val) elif typeuri in ('dateTime'): return np.datetime64, datetime.fromisoformat(val) elif typeuri in ('date'): return pd.date, date.fromisoformat(val) elif typeuri in ('time'): return pd.time, time.fromisoformat(val) return 'object', val
def __convert_datetime(element: str, form: str): # if element is None return None if not element: return None if form == "Datetime": # if element contains timezone information etc, strip them if len(element) != 19: element = element[:19] # replace possible 'T' with a space element = element.replace("T", " ") return datetime.strptime(element, "%Y-%m-%d %H:%M:%S") elif form == "Time": # strip milliseconds, timezone if len(element) != 8: element = element[:8] return time.fromisoformat(element) elif form == "Date": return date.fromisoformat(element) else: raise Exception( f"Invalid values passed to convert_datetime: {element, form}")
def standup_time(self): """ Calculate the standup window stop time """ do_yesterday = True now = datetime.now(timezone.utc) standup_at = time.fromisoformat('15:00:00') standup_today = datetime( now.year, now.month, now.day, standup_at.hour, standup_at.minute, standup_at.second, tzinfo=timezone.utc, ) standup_tomorrow = standup_today + timedelta(days=1) standup_has_already_happened_today = now > standup_today if standup_has_already_happened_today and not do_yesterday: standup_next = standup_tomorrow else: standup_next = standup_today return standup_next
def load_csv(csv_file: Path) -> List[Dict[str, Any]]: result: List[Dict[str, Any]] = [] temp: Dict[str, Any] = {} with open(csv_file, mode='r', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: for k, v in row.items(): try: if '-' in v and ':' in v: x = datetime.fromisoformat(v) elif '-' in v and v[0] != '-': x = date.fromisoformat(v) elif ':' in v: x = time.fromisoformat(v) elif '.' in v: x = float(v) else: x = int(v) temp[k] = x except ValueError: temp[k] = v result.append(copy.deepcopy(temp)) return result
def start(verbosity): fmt = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' if verbosity: logging.basicConfig(level=verbosity, format=fmt, stream=sys.stderr) else: logging.basicConfig(level=settings.log_level, format=fmt, stream=sys.stderr) _LOGGER.info(settings.to_dict()) scheduler.add_listener(executed_job, EVENT_JOB_EXECUTED) _init_time = time.fromisoformat(settings.init_time) scheduler.add_job(generate_transitions, trigger=CronTrigger(hour=_init_time.hour, minute=_init_time.minute, second=_init_time.second), max_instances=1) scheduler.start() app.run(host=settings.server_address, port=settings.server_port, debug=False)
def from_standard_time(cls, standard_time): """ Takes a time object and converts to decimal. :param standard_time: datetime.time :return: string """ midnight = datetime.combine(date.today(), time.fromisoformat('00:00:00')) target = datetime.combine(date.today(), standard_time) standard_seconds = (target - midnight).seconds second_ratio = 100 * 100 * 10 / (60 * 60 * 24) decimal_seconds = floor(standard_seconds * second_ratio) seconds_per_hour = 100 * 100 seconds_per_minute = 100 hour = decimal_seconds // seconds_per_hour decimal_seconds -= hour * seconds_per_hour minute = decimal_seconds // seconds_per_minute decimal_seconds -= minute * seconds_per_minute return cls(hour, minute, decimal_seconds)
def _parse_buyer(self, data, buyer=None): user_id, buying_place, buying_country, buying_city, buying_street, buying_geo_long, buying_geo_lat, buying_time, buying_date, ship_place, ship_country, ship_city, ship_street, ship_geo_long, ship_geo_lat, ship_time, ship_date, current_address, current_country, current_city, current_street, current_geo_long, current_geo_lat, search_radius, search_place, shopping_cost, shipping_cost = None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None user_id = data['user_id'] if 'buying_place' in data: buying_place = str(data['buying_place']) if 'buying_country' in data: buying_country = str(data['buying_country']) if 'buying_city' in data: buying_city = str(data['buying_city']) if 'buying_street' in data: buying_street = str(data['buying_street']) if 'buying_geo_long' in data: buying_geo_long = float(data['buying_geo_long']) if 'buying_geo_lat' in data: buying_geo_lat = float(data['buying_geo_lat']) if 'buying_date' in data: try: buying_date = date.fromisoformat(data['buying_date']) except Exception as e: print(e.__str__()) buying_date = datetime.now().date() if 'buying_time' in data: try: buying_time = time.fromisoformat(data['buying_time']) except Exception as e: print(e.__str__()) buying_time = datetime.now().time() if 'ship_place' in data: ship_place = data['ship_place'] if 'ship_country' in data: ship_country = data['ship_country'] if 'ship_city' in data: ship_city = data['ship_city'] if 'ship_street' in data: ship_street = data['ship_street'] if 'ship_geo_long' in data: ship_geo_long = float( data['ship_geo_long']) # xu ly ngoai le cho nay sau if 'ship_geo_lat' in data: ship_geo_lat = float(data['ship_geo_lat']) if 'ship_date' in data: try: ship_date = date.fromisoformat(data['ship_date']) except Exception as e: print(e.__str__()) ship_date = datetime.now().date() if 'ship_time' in data: try: ship_time = time.fromisoformat(data['ship_time']) except Exception as e: print(e.__str__()) ship_time = datetime.now().time() if 'current_address' in data: current_address = data['current_address'] if 'current_country' in data: current_country = data['current_country'] if 'current_city' in data: current_city = data['current_city'] if 'current_street' in data: current_street = data['current_street'] if 'current_geo_long' in data: current_geo_long = float(data['current_geo_long']) if 'current_geo_lat' in data: current_geo_lat = float(data['current_geo_lat']) if 'search_radius' in data: search_radius = float(data['search_radius']) if 'search_place' in data: search_place = data['search_place'] if 'shopping_cost' in data: shopping_cost = float(data['shopping_cost']) if 'shipping_cost' in data: shipping_cost = float(data['shipping_cost']) if buyer is None: buyer = Buyer(user_id=user_id, buying_place=buying_place, buying_country=buying_country, buying_city=buying_city, buying_street=buying_street, buying_geo_long=buying_geo_long, buying_geo_lat=buying_geo_lat, buying_time=buying_time, buying_date=buying_date, ship_place=ship_place, ship_country=ship_country, ship_city=ship_city, ship_street=ship_street, ship_geo_long=ship_geo_long, ship_geo_lat=ship_geo_lat, ship_time=ship_time, ship_date=ship_date, current_address=current_address, current_country=current_country, current_city=current_city, current_street=current_street, current_geo_long=current_geo_long, current_geo_lat=current_geo_lat, search_radius=search_radius, search_place=search_place, shopping_cost=shopping_cost, shipping_cost=shipping_cost) else: # buyer.user_id, buyer.buying_place, buyer.buying_time, buyer.buying_date, buyer.desired_place_ship, buyer.desired_time_ship, buyer.desired_date_ship, buyer.search_radius, buyer.search_place, buyer.shopping_cost, buyer.shipping_cost = user_id, buying_place, buying_time, buying_date, desired_place_ship, desired_time_ship, desired_date_ship, search_radius, search_place, shopping_cost, shipping_cost # buyer.order_id = buyer.user_id = user_id buyer.buying_place = buying_place buyer.buying_country = buying_country buyer.buying_city = buying_city buyer.buying_street = buying_street buyer.buying_geo_long = buying_geo_long buyer.buying_geo_lat = buying_geo_lat buyer.buying_time = buying_time buyer.buying_date = buying_date buyer.ship_place = ship_place buyer.ship_country = ship_country buyer.ship_city = ship_city buyer.ship_street = ship_street buyer.ship_geo_long = ship_geo_long buyer.ship_geo_lat = ship_geo_lat buyer.ship_time = ship_time buyer.ship_date = ship_date buyer.current_address = current_address buyer.current_country = current_country buyer.current_city = current_city buyer.current_street = current_street buyer.current_geo_long = current_geo_long buyer.current_geo_lat = current_geo_lat buyer.search_radius = search_radius buyer.search_place = search_place buyer.shopping_cost = shopping_cost buyer.shipping_cost = shipping_cost return buyer
def convert_iso_string_to_time_delta(iso_string: str): """ Inspired by https://stackoverflow.com/questions/35241643/convert-datetime-time-into-datetime-timedelta-in-python-3-4 """ string_as_time = time.fromisoformat(iso_string) return datetime.combine(date.min, string_as_time) - datetime.min
def initialize(self) -> None: """Initialize a room with AutoMoLi.""" self.room = str(self.args.get("room")) # self.delay = int(self.args.get("delay", DEFAULT_DELAY)) delay = int(self.args.get("delay", DEFAULT_DELAY)) self.event_motion = self.args.get("motion_event", None) self.motion_state_on = self.args.get("motion_state_on", None) self.motion_state_off = self.args.get("motion_state_off", None) # devices self.lights: Set[str] = self.args.get("lights", set()) self.sensors_motion: Set[str] = self.args.pop("motion", set()) self.sensors_illuminance: Set[str] = self.args.pop( "illuminance", set()) self.sensors_humidity: Set[str] = self.args.pop("humidity", set()) # device config self.illuminance_threshold: Optional[int] = self.args.get( "illuminance_threshold") self.humidity_threshold: Optional[int] = self.args.get( "humidity_threshold") # on/off switch via input.boolean self.disable_switch_entity = self.args.get("disable_switch_entity") # use user-defined daytimes if available daytimes: List[Dict[str, Union[int, str]]] = self.args.get( "daytimes", DEFAULT_DAYTIMES) # currently active daytime settings self.active: Dict[str, Union[int, str]] = {} self._handle = None # define light entities switched by automoli if self.lights: self.lights = set(self.lights) elif self.entity_exists(f"light.{self.room}"): self.lights.update([f"light.{self.room}"]) else: self.lights.update(self.find_sensors(KEYWORD_LIGHTS)) # define sensor entities monitored by automoli if not self.sensors_motion: self.sensors_motion.update(self.find_sensors(KEYWORD_SENSORS)) # enumerate humidity sensors if threshold given if self.humidity_threshold: if not self.sensors_humidity: self.sensors_humidity.update( self.find_sensors(KEYWORD_SENSORS_HUMIDITY)) if not self.sensors_humidity: self.log( f"No humidity sensors given/found ('{KEYWORD_SENSORS_HUMIDITY}') ", f"→ disabling humidity threshold blocker.", ) self.humidity_threshold = None # enumerate illuminance sensors if threshold given if self.illuminance_threshold: if not self.sensors_illuminance: self.sensors_illuminance.update( self.find_sensors(KEYWORD_SENSORS_ILLUMINANCE)) if not self.sensors_illuminance: self.log( f"No illuminance sensors given/found ", f"('{KEYWORD_SENSORS_ILLUMINANCE}') → ", f"disabling illuminance threshold blocker.", ) self.illuminance_threshold = None # sanity check if not self.sensors_motion: raise ValueError( f"No sensors given/found, sorry! ('{KEYWORD_SENSORS}')") elif not self.lights: raise ValueError( f"No sensors given/found, sorry! ('{KEYWORD_LIGHTS}')") starttimes: Set[time] = set() # build daytimes dict for idx, daytime in enumerate(daytimes): dt_name = daytime.get("name", f"{DEFAULT_NAME}_{idx}") dt_delay = daytime.get("delay", delay) dt_light_setting = daytime.get("light", DEFAULT_LIGHT_SETTING) dt_is_hue_group = (isinstance(dt_light_setting, str) and not dt_light_setting.startswith("scene.") and any([ self.get_state(entity_id=entity, attribute="is_hue_group") for entity in self.lights ])) py37_or_higher = sys.version_info.major >= 3 and sys.version_info.minor >= 7 dt_start: time try: if py37_or_higher: dt_start = time.fromisoformat(str( daytime.get("starttime"))) else: dt_start = self.datetime.strptime( str(daytime.get("starttime")), "%H:%M").time() except ValueError as error: raise ValueError( f"missing start time in daytime '{dt_name}': {error}") # configuration for this daytime daytime = dict( daytime=dt_name, delay=dt_delay, # starttime=dt_start, # datetime is not serializable starttime=dt_start.isoformat(), light_setting=dt_light_setting, is_hue_group=dt_is_hue_group, ) # info about next daytime if py37_or_higher: next_dt_start = time.fromisoformat( str(daytimes[(idx + 1) % len(daytimes)].get("starttime"))) else: next_dt_start = self.datetime.strptime( str(daytimes[(idx + 1) % len(daytimes)].get("starttime")), "%H:%M").time() # collect all start times for sanity check if dt_start in starttimes: raise ValueError( f"Start times of all daytimes have to be unique! ", f"Duplicate found: {dt_start}", ) starttimes.add(dt_start) # check if this daytime should ne active now if self.now_is_between(str(dt_start), str(next_dt_start)): self.switch_daytime(dict(daytime=daytime, initial=True)) self.args["active_daytime"] = daytime.get("daytime") # schedule callbacks for daytime switching self.run_daily(self.switch_daytime, dt_start, random_start=-10, **dict(daytime=daytime)) # set up event listener for each sensor for sensor in self.sensors_motion: # listen to xiaomi sensors by default if not any([self.motion_state_on, self.motion_state_off]): self.listen_event(self.motion_event, event=EVENT_MOTION_XIAOMI, entity_id=sensor) self.refresh_timer() # do not use listen event and listen state below together continue # on/off-only sensors without events on every motion if self.motion_state_on and self.motion_state_off: self.listen_state(self.motion_detected_state, entity=sensor, new=self.motion_state_on) self.listen_state(self.motion_cleared_state, entity=sensor, new=self.motion_state_off) # listen for non-xiaomi events if self.event_motion: self.log( f"\nPlease update your config to use `motion_state_on/off'\n" ) # display settings self.args.setdefault("listeners", self.sensors_motion) self.args.setdefault("sensors_illuminance", list(self.sensors_illuminance) ) if self.sensors_illuminance else None self.args.setdefault("sensors_humidity", list( self.sensors_humidity)) if self.sensors_humidity else None self.args["daytimes"] = daytimes # init adutils self.adu = ADutils(APP_NAME, self.args, icon=APP_ICON, ad=self, show_config=True)
from datetime import time print(time.fromisoformat('12:34:56'))
def str_to_time(value: Optional[str]) -> Optional[datetime.time]: if value is not None: dt_value = time_cls.fromisoformat(value) else: dt_value = None return dt_value
print(artista) print("\n") stop_time = getTime() stop_memory = getMemory() tracemalloc.stop() delta_time = stop_time - start_time delta_memory = deltaMemory(start_memory, stop_memory) print(str(delta_time) + " " + str(delta_memory)) elif int(inputs[0]) == 6: minimo = t.fromisoformat( input( "Ingrese el limite inferior del intervalo de tiempo que desea consultar-> " )) maximo = t.fromisoformat( input( "Ingrese el limite superior del intervalo de tiempo que desea consultar-> " )) delta_time = -1.0 delta_memory = -1.0 tracemalloc.start() start_time = getTime() start_memory = getMemory() output = controller.req5(catalog, minimo, maximo)
class AllowOrdersUntil(TimePreference): name = "allow_orders_until" default = time.fromisoformat("11:00")
async def pills_check(): """ Check pills from db every 5 minutes and send notifications if need :return: """ logger.info("pills check started") db = SingletonClient.get_data_base() now = datetime(2021, 1, 1, datetime.now().hour, datetime.now().minute) if now.hour == 0 and now.minute == 0: result = await db.Pills.update_many({}, {"$set": {"time_status": []}}) async for pill in db.Pills.find({"paused": {"$ne": True}}): user = await db.Users.find_one({"_id": ObjectId(pill.get("user"))}) time_status = pill.get("time_status") logger.info(pill) for num, ti in enumerate(pill.get("time_list")): t = time.fromisoformat(ti) t = datetime(2021, 1, 1, t.hour, t.minute) if t > now: continue try: status = time_status[num] except IndexError: status = False time_status.append(False) if status: # if user accept time don't send notification continue _t = datetime(2021, 1, 1, t.hour, t.minute) + timedelta(hours=1) if now > _t: # If more than one hour has elapsed after taking the pill and the person has not taken it time_status[num] = True else: text = "You have to take <b>{}</b> pill at {}.".format( pill.get("title"), ti) markup = types.InlineKeyboardMarkup() markup.add( types.InlineKeyboardButton( "I took 💊", callback_data=f"took,{pill.get('_id')},{ti}")) try: await bot.send_message(user.get("telegram_id"), text=text, reply_markup=markup) except BotBlocked: result = await db.Pills.delete_many( {'user': pill.get("user")}) return logger.info( f"Bot blocked by user user_id={user.get('telegram_id')} pill_id={pill.get('_id')} " f"delete result={result.acknowledged} delete count={result.deleted_count}" ) result = await db.Pills.update_one( {"_id": ObjectId(pill.get("_id"))}, {"$set": { "time_status": time_status }}) logger.info( f"user_id={user.get('telegram_id')} pill_id={pill.get('_id')} " f"update_one result={result.acknowledged} time_status={time_status}" )
def time_constructor(loader: yaml.Loader, node: yaml.ScalarNode) -> time: value = loader.construct_scalar(node) data = time.fromisoformat(value) return data
def main(): # Arguments parsing parser = argparse.ArgumentParser( "All arguments are optional and read from config.ini when not passed.") parser.add_argument("-d", "--debug", action="count", default=0, help="Increase debugging level") parser.add_argument("-c", "--config", default='config.ini', help="Configuration file") parser.add_argument("-s", "--start-date", default="", help="Start date for sync in YYYY-MM-DD format") parser.add_argument("-e", "--end-date", default="", help="End data for sync in YYYY-MM-DD format") parser.add_argument("-g", "--google-creds", default="auth/google.json", help="Google credentials file") parser.add_argument("-f", "--fitbit-creds", default="auth/fitbit.json", help="Fitbit credentials file") parser.add_argument("-v", "--version", help="Fitbit-GoogleFit migration tool version", action="store_true") args = parser.parse_args() # Show version information if required if args.version: print(' fitbit-googlefit version {}'.format(VERSION)) print('') # Reading configuration from config file config = configparser.ConfigParser() config.read(args.config) params = config['params'] # Init objects helper = Helper(args.fitbit_creds, args.google_creds) weighTime = time.fromisoformat(params.get('weigh_time')) convertor = Convertor(args.google_creds, params.get('project_number'), None, weighTime) fitbitClient, googleClient = helper.GetFitbitClient( ), helper.GetGoogleClient() remote = Remote(fitbitClient, googleClient, convertor, helper) # Get user's time zone info from Fitbit -- since Fitbit time stamps are not epoch and stored in user's timezone. userProfile = remote.ReadFromFitbit(fitbitClient.user_profile_get) tzinfo = dateutil.tz.gettz(userProfile['user']['timezone']) convertor.UpdateTimezone(tzinfo) # setup Google Fit data sources for each data type supported for dataType in [ 'steps', 'distance', 'weight', 'heart_rate', 'calories', 'activity', 'body_fat', 'sleep' ]: remote.CreateGoogleFitDataSource(dataType) # Decide the start and end dates of sync start_date_str = args.start_date if args.start_date != '' else params.get( 'start_date') end_date_str = args.end_date if args.end_date != '' else params.get( 'end_date') start_date = convertor.parseHumanReadableDate(start_date_str) end_date = convertor.parseHumanReadableDate(end_date_str) # Start syncing data for the given range for single_date in convertor.daterange(start_date, end_date): date_stamp = single_date.strftime(DATE_FORMAT) print('------------------------------ {} -------------------------'. format(date_stamp)) #---------------------------------- steps ------------------------ if params.getboolean('sync_steps'): remote.SyncFitbitToGoogleFit('steps', date_stamp) #---------------------------------- distance ------------------------ if params.getboolean('sync_distance'): remote.SyncFitbitToGoogleFit('distance', date_stamp) #---------------------------------- heart rate ------------------------ if params.getboolean('sync_heartrate'): remote.SyncFitbitToGoogleFit('heart_rate', date_stamp) #---------------------------------- weight ------------------------ if params.getboolean('sync_weight'): remote.SyncFitbitToGoogleFit('weight', date_stamp) #---------------------------------- body fat ------------------------ if params.getboolean('sync_body_fat'): remote.SyncFitbitToGoogleFit('body_fat', date_stamp) #---------------------------------- calories ------------------------ if params.getboolean('sync_calories'): remote.SyncFitbitToGoogleFit('calories', date_stamp) #---------------------------------- sleep ------------------------ if params.getboolean('sync_sleep'): remote.SyncFitbitToGoogleFit('sleep', date_stamp) print('') #---------------------------------- activity logs ------------------------ if params.getboolean('sync_activities'): remote.SyncFitbitActivitiesToGoogleFit(start_date=start_date)
)) elif death_entry := DEATH_FORMAT.match(entry): # Since the death format is *too* flexible, it captures things # that are not deaths. We can filter those out by identifying # ones that start with words that are not player names. # # Note: We could consider switching this around and instead # build a comprehensive list of potential death messages for an # allowlist instead, as suggested by inchoation. if (player := death_entry.group('player')) in NOT_PLAYERS: continue event_stream.append( PlayerDeath( time=datetime.combine( log_date, time.fromisoformat(death_entry.group('time'))), player=player, cause=death_entry.group('cause'), )) elif message_entry := MESSAGE_FORMAT.match(entry): event_stream.append( PlayerMessage( time=datetime.combine( log_date, time.fromisoformat(message_entry.group('time'))), player=message_entry.group('player'), message=message_entry.group('message'), )) # Write some CSVs if not os.path.exists('output'):
def _parse_order(self, data, order=None): buyer_id, supplier_id, date_created, time_created, accepted, status, price, rate, comment, ship_price_buyer, ship_price_supplier, ship_price = None, None, None, None, None, None, None, None, None, None, None, None if 'buyer_id' in data: try: buyer_id = int(data['buyer_id']) except Exception as e: print(e.__str__()) pass if 'supplier_id' in data: try: supplier_id = int(data['supplier_id']) except Exception as e: print(e.__str__()) pass if 'date_created' in data: try: date_created = date.fromisoformat(data['date_created']) except Exception as e: print(e.__str__()) date_created = datetime.datetime.now().date() if 'time_created' in data: try: time_created = time.fromisoformat(data['time_created']) except Exception as e: print(e.__str__()) time_created = datetime.datetime.now().time() if 'accepted' in data: try: accepted = bool(data['accepted']) except Exception as e: print(e.__str__()) accepted = False if 'status' in data: status = data['status'] else: status = 'open' if 'price' in data: try: price = float(data['price']) except Exception as e: print(e.__str__()) pass if 'rate' in data: try: rate = int(data['rate']) except Exception as e: print(e.__str__()) pass if 'comment' in data: comment = data['comment'] if 'ship_price_buyer' in data: try: ship_price_buyer = float(data['ship_price_buyer']) except Exception as e: print(e.__str__()) pass if 'ship_price_supplier' in data: try: ship_price_supplier = float(data['ship_price_supplier']) except Exception as e: print(e.__str__()) pass if 'ship_price' in data: try: ship_price = float(data['ship_price']) except Exception as e: print(e.__str__()) pass if order is None: order = Order(buyer_id=buyer_id, supplier_id=supplier_id, date_created=date_created, time_created=time_created, accepted=accepted, status=status, price=price, rate=rate, comment=comment, ship_price_buyer=ship_price_buyer, ship_price_supplier=ship_price_supplier, ship_price=ship_price) else: order.buyer_id = buyer_id order.supplier_id = supplier_id order.date_created = date_created order.time_created = time_created order.accepted = accepted order.status = status order.price = price order.rate = rate order.comment = comment order.ship_price_buyer = ship_price_buyer order.ship_price_supplier = ship_price_supplier order.ship_price = ship_price return order
def get_random_time(): time1 = exrex.getone( '(0[1-9]|1[0-9]|2[0-3]):(0[1-9]|[1-5][0-9]):(0[1-9]|[1-5][0-9])') return time.fromisoformat(time1)
def parse_time(time_str: str): try: return time.fromisoformat(time_str).replace(tzinfo=timezone( timedelta(hours=3))) # TODO: this timezone is temporary except ValueError: raise CommandException(ERRMSG_WRONG_TIME_FORMAT)
def main(): print("Starting RPC...") rpc = RPC(673133177274892290) rpc.start() try: start = None end = None pos = [] est = "None" state = 0 sys = system() # Find Minecraft game dir if sys == "Windows": file = Path("AppData") / "Roaming" / ".minecraft" elif sys == "Darwin": file = Path("Library") / "Application Support" / "minecraft" elif sys == "Linux": file = ".minecraft" else: print("Unknown system, unable to find game dir") file = Path.home() / file / "logs" / "latest.log" with open(file ) as f: # TODO: Read previous logs if data is insufficient. while True: line = f.readline() if line: text = line[11:-1] try: t = datetime.combine(date.today(), time.fromisoformat( line[1:9])).timestamp() if text.startswith("[main/INFO]: Connecting to "): end = None est = "None" state = 1 elif text == "[main/INFO]: [CHAT] 2b2t is full": start = int(t) pos = [] state = 2 elif text.startswith( "[main/INFO]: [CHAT] Position in queue: "): p = int(text[39:]) pos.append((t, p)) if len(pos) == 61: pos[0:1] = [] if len(pos) == 60: if pos[0][1] == p: est = "never" else: est = "" seconds = (t - pos[0][0]) / ( pos[0][1] - p ) # FIXME: Time is negative when you're a time traveller. seconds = int( seconds * p) # TODO: Rework the estimations. days = seconds // 86400 if days: est += f"{days}d " hours = seconds % 86400 // 3600 if hours: est += f"{hours}h " est += f"{seconds % 3600 // 60}m" if state == 2: state = 3 elif (text == "[main/INFO]: [CHAT] Connecting to the server..." or text.startswith("[main/INFO]: Loaded ")): pos = [] start = int(t) state = 4 elif text.startswith( "[main/INFO]: [CHAT] [SERVER] Server restarting in " ): if text.endswith(" minutes..."): end = int(t) + 600 * int(text[50:-12]) elif text.endswith(" seconds..."): end = int(t) + 10 * int(text[50:-11]) elif text.endswith(" second..."): end = int(t) + 10 * int(text[50:-10]) state = 5 elif text == "[main/INFO]: Stopping!": print("Hi!") break except ValueError: pass else: if state == 1: rpc.set_activity( large_image="image", large_text="2b2t.org", details="Connecting...", ) elif state == 2: rpc.set_activity( large_image="image", large_text="2b2t.org", details="Waiting in queue", start=start, ) elif state == 3: rpc.set_activity( large_image="image", large_text="2b2t.org", details=f"Position in queue: {pos[-1][1]}", state="Estimated time: " + est, start=start, ) sleep(10) elif state == 4: rpc.set_activity( large_image="image", large_text="2b2t.org", details="Playing", start=start, ) elif state == 5: rpc.set_activity( large_image="image", large_text="2b2t.org", details=f"Waiting for restart...", state=f"Position in queue: {pos[-1][1]}", end=end, ) if stat(f.fileno()).st_nlink == 0: f.close() f = open(file) except KeyboardInterrupt: pass finally: print("\nStopping RPC...") rpc.close()
class ShowTodayDishesUntil(TimePreference): name = "show_today_dishes_until" default = time.fromisoformat("16:00")
def parse_time(val: Any) -> time: value = str(val, encoding=DEFAULT_CHARSET) if type(val) is bytes else val return time.fromisoformat(value)
def manage_tournaments(): if request.method == 'GET': discipline = request.args.get('discipline', '') tournament_type = request.args.get('type') lower_date = request.args.get('lower_date') upper_date = request.args.get('upper_date') lower_time = request.args.get('lower_time') upper_time = request.args.get('upper_time') discipline_filter = f'%{discipline}%' query = Tournament.query.filter( Tournament.discipline.ilike(discipline_filter)) if tournament_type is not None: query = query.filter( Tournament.type == TournamentType[tournament_type]) tournaments = query.all() if lower_date is not None: tournaments = [ tour for tour in tournaments if tour.start_time >= datetime.fromisoformat(lower_date) ] if upper_date is not None: tournaments = [ tour for tour in tournaments if tour.start_time <= datetime.fromisoformat(upper_date) ] if lower_time is not None: tournaments = [ tour for tour in tournaments if tour.start_time.time() >= time.fromisoformat(lower_time) ] if upper_time is not None: tournaments = [ tour for tour in tournaments if tour.start_time.time() <= time.fromisoformat(upper_time) ] return jsonify(tournaments=[{ 'id': tour.id, 'title': tour.title, 'logo': tour.logo, 'discipline': tour.discipline, 'discipline_type': tour.discipline_type.name, 'type': tour.type.name, 'start_time': tour.start_time.isoformat(), 'state': tour.state.name, 'creator': tour.creator.vk_id, } for tour in tournaments]) # POST new_tournament = Tournament( title=request.json['title'], logo=request.json.get('logo'), discipline=request.json['discipline'], discipline_type=DisciplineType[request.json['discipline_type']], type=TournamentType[request.json['type']], start_time=datetime.fromisoformat(request.json['start_time']), state='planned', user_id=g.user.id, ) db.session.add(new_tournament) db.session.commit() return jsonify(tournament_id=new_tournament.id)
def deserialize(feat, data, geom_format='wkt', dt_format='obj', transformer=None): if 'geom' in data: try: if geom_format == 'wkt': feat.geom = Geometry.from_wkt(data['geom']) elif geom_format == 'geojson': feat.geom = Geometry.from_geojson(data['geom']) else: raise ValidationError( _("Geometry format '%s' is not supported.") % geom_format) except GeometryNotValid: raise ValidationError(_("Geometry is not valid.")) if transformer is not None: feat.geom = transformer.transform(feat.geom) if dt_format not in ('obj', 'iso'): raise ValidationError( _("Date format '%s' is not supported.") % dt_format) if 'fields' in data: fdata = data['fields'] for fld in feat.layer.fields: if fld.keyname in fdata: val = fdata.get(fld.keyname) if val is None: fval = None elif fld.datatype == FIELD_TYPE.DATE: if dt_format == 'iso': fval = date.fromisoformat(val) else: fval = date(int(val['year']), int(val['month']), int(val['day'])) elif fld.datatype == FIELD_TYPE.TIME: if dt_format == 'iso': fval = time.fromisoformat(val) else: fval = time(int(val['hour']), int(val['minute']), int(val['second'])) elif fld.datatype == FIELD_TYPE.DATETIME: if dt_format == 'iso': fval = datetime.fromisoformat(val) else: fval = datetime(int(val['year']), int(val['month']), int(val['day']), int(val['hour']), int(val['minute']), int(val['second'])) else: fval = val feat.fields[fld.keyname] = fval if 'extensions' in data: for cls in FeatureExtension.registry: if cls.identity in data['extensions']: ext = cls(feat.layer) ext.deserialize(feat, data['extensions'][cls.identity])
from moviepy.config import get_setting from moviepy.tools import subprocess_call def ffmpeg_extract_subclip(filename, t1, t2, targetname=None): """ Makes a new video file playing video file ``filename`` between the times ``t1`` and ``t2``. """ name, ext = os.path.splitext(filename) if not targetname: T1, T2 = [int(1000 * t) for t in [t1, t2]] targetname = "%sSUB%d_%d.%s" % (name, T1, T2, ext) cmd = [ get_setting("FFMPEG_BINARY"), "-y", "-ss", "%0.2f" % t1, "-i", filename, "-t", "%0.2f" % (t2 - t1), "-map", "0", "-vcodec", "copy", "-acodec", "copy", targetname ] subprocess_call(cmd) name = sys.argv[1] Str_start = time.fromisoformat(("{0}".format(sys.argv[2])).replace(',', '.')) Str_end = time.fromisoformat(("{0}".format(sys.argv[3])).replace(',', '.')) start = Str_start.hour * 3600 + Str_start.minute * 60 + Str_start.second end = Str_end.hour * 3600 + Str_end.minute * 60 + Str_end.second ffmpeg_extract_subclip('{0}'.format(name), start, end, 'Cut-{0}'.format(name))
timedelta: timedelta @attr.s(auto_attribs=True) class CATTRClass: list_simple: List[CATTRSimpleClass] list_enum: List[CATTREnumClass] tuple_datetime: Tuple[CATTRDateTimeClass, ...] dict_complex: Dict[ int, Mapping[str, MutableMapping[UUID, Sequence[Decimal]]] ] converter = cattr.Converter() converter.register_structure_hook( datetime, lambda s, _: datetime.fromisoformat(s) ) converter.register_structure_hook(date, lambda s, _: date.fromisoformat(s)) converter.register_structure_hook(time, lambda s, _: time.fromisoformat(s)) converter.register_structure_hook(timedelta, lambda i, _: timedelta(seconds=i)) converter.register_structure_hook(UUID, lambda s, _: UUID(s)) converter.register_structure_hook(Decimal, lambda s, _: Decimal(s)) converter.register_unstructure_hook(datetime, lambda x: x.isoformat()) converter.register_unstructure_hook(date, lambda x: x.isoformat()) converter.register_unstructure_hook(time, lambda x: x.isoformat()) converter.register_unstructure_hook(timedelta, lambda x: x.total_seconds()) converter.register_unstructure_hook(UUID, lambda x: str(x)) converter.register_unstructure_hook(Decimal, lambda x: str(x))