Ejemplo n.º 1
0
    def test__ApiMetricStorage_insertPlantData__someData(self):
        self.createPlant()
        time = datetime.datetime.now(datetime.timezone.utc)

        plant_data = {
            "plant":
            "alibaba",
            "version":
            "1.0",
            "time":
            time.isoformat(),
            "devices": [{
                "id":
                "SensorTemperatureAmbient:benjami",
                "readings": [{
                    "temperature_dc": 120,
                    "time": time.isoformat(),
                }]
            }]
        }

        apiClient = self.createApiClient()
        result = apiClient.insertPlantData(plant_data)
        print(result)
        # expectedResponse = {"detail":[{"loc":["body","time"],"msg":"OK","type":"None"},{"loc":["body","devices"],"msg":"OK","type":"None"}]}

        self.assertDictEqual(result, plant_data)
Ejemplo n.º 2
0
def serial_ports():
    if sys.platform.startswith('win'):
        ports = ['COM' + str(i + 1) for i in range(256)]

    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        ports = glob.glob('/dev/tty[A-Za-z]*')

    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')

    else:
        time = datetime.datetime.now()
        string = time.isoformat(
        ) + " : Error, operating system not supported (not Mac, Linux or Windows)\n" + str(
            e)
        logging.error(string)
        print("Error, operating system not supported, exiting...")
        sys.exit(-3)

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result
Ejemplo n.º 3
0
    def __scan_start(self, isCal=False):
        if self.settings.mode == Mode.SINGLE:
            if self.__save_warn(Warn.SCAN):
                return False

        if not self.threadScan:
            self.__set_control_state(False)
            samples = calc_samples(self.settings.dwell)
            self.status.set_info('')
            self.scanInfo.setFromSettings(self.settings)
            time = datetime.datetime.utcnow().replace(microsecond=0)
            self.scanInfo.time = time.isoformat() + "Z"
            self.scanInfo.lat = None
            self.scanInfo.lon = None
            self.scanInfo.desc = ''
            self.stopAtEnd = False
            self.stopScan = False
            self.threadScan = ThreadScan(self, self.sdr, self.settings,
                                         self.settings.indexRtl, samples, isCal)
            self.filename = "Scan {0:.1f}-{1:.1f}MHz".format(self.settings.start,
                                                            self.settings.stop)
            self.graph.set_plot_title()

            if self.settings.gps:
                if self.threadLocation and self.threadLocation.isAlive():
                    self.threadLocation.stop()
                    self.threadLocation.join()
                device = self.settings.devicesGps[self.settings.indexGps]
                self.threadLocation = ThreadLocation(self, device)

            return True
Ejemplo n.º 4
0
def formatShowSched():
	for i in range(2):
	# 	with open('/home/bryan/disney/dumps/' + park_index[i] + '/charactertime.json') as data_file:
		show_list = [] 
		time = datetime.datetime.now()
		show_list.append({'updated_at':time.isoformat()})
		with open('Disney/' + park_index[i] + '/showlist.json') as data_file:
			try:
				data = json.load(data_file)
				for entry in data:
					temparr = {'Name':strip_unicode(entry['Name']), 'Location':strip_unicode(entry['Subtitle']), 'Hours':strip_unicode(strip_tags(entry['CardContent']).replace("Nothing left today", "Concluded"))}
					show_list.append(temparr)

				if i == 0:
					output = open('Disney/dl_showtime' + '.json', 'w')
				elif i == 1:
					output = open('Disney/dca_showtime' + '.json', 'w')
				output.write(json.dumps(show_list))
				output.close()
			except ValueError, e:
				if i == 0:
					output = open('Disney/dl_showtime' + '.json', 'w')
				elif i == 1:
					output = open('Disney/dca_showtime' + '.json', 'w')
				output.write(json.dumps(show_list))
				output.close()
Ejemplo n.º 5
0
def send_session(sid, user_id, dsn, time, release, **kwargs):
    """
    Creates an envelope payload for a session and posts it to Relay
    """
    formated_time = time.isoformat()
    envelope_headers = "{}"
    item_headers = json.dumps({"type": "session"})
    data = {
        "sid": sid,
        "did": str(user_id),
        "started": formated_time,
        "duration": random.randrange(2, 60),
        "attrs": {
            "release": release,
            "environment": "prod",
        },
    }
    data.update(**kwargs)
    core = json.dumps(data)

    body = f"{envelope_headers}\n{item_headers}\n{core}"
    endpoint = dsn.get_endpoint()
    url = f"{endpoint}/api/{dsn.project_id}/envelope/?sentry_key={dsn.public_key}&sentry_version=7"
    resp = requests.post(url=url, data=body)
    resp.raise_for_status()
Ejemplo n.º 6
0
def format(time):
	class TZ(tzinfo):
		def utcoffset(self, dt): 
			return timedelta(minutes=+330)	# For India
	
	time = time.replace(tzinfo = TZ(), microsecond=0)
	return time.isoformat('T')
Ejemplo n.º 7
0
 def bind(self):
     try:
         rowCount = 0
         while True:
             #response = ''                               
             if self.serialCon.inWaiting():
                 # get serial data
                 incommingbyte = self.serialCon.read()                  
                 if incommingbyte == '\r': # skip this
                     continue
                 # insert timestamp
                 if incommingbyte == '\n':
                     time = datetime.datetime.now()
                     self.data = self.data + ' timestamp ' + time.isoformat()
                     rowCount = rowCount + 1
                 sys.stdout.write(incommingbyte)    
                 self.data = self.data + incommingbyte
                 
                 
                 # back up data
                 if rowCount >= self.backupRowCount:
                     print '...backup'
                     self.exportCSV('backup.csv')
                     rowCount = 0;
                     #print response.replace('\r','\n').rstrip()
             
     except serial.SerialException:
         print 'error:', sys.exc_info()	
     except KeyboardInterrupt:
         print '...binding terminated!'	        
     finally:
         self.serialCon.flushInput()
         self.serialCon.flushOutput()
Ejemplo n.º 8
0
    def set_dir_path(self, dir, delFlag):
        
        if os.path.exists(dir):
            stat_dir = dir+"/stats"
            if os.path.exists(stat_dir):
                if delFlag == True :
                    # create a backup with timestamp.
                    time = datetime.datetime.now()
                    shutil.copytree(stat_dir, stat_dir+'_'\
                            +unicode('_'.join(time.isoformat().split(':'))))
                    shutil.rmtree(dir+"/stats")
                    os.makedirs(dir+"/stats")
                else : pass
            else:
                os.makedirs(dir+"/stats")
        else : 
            print 'There is no dirctory {0}'.format(dir)
            sys.exit(0)

        self.src_path = dir
        self.log_dir = self.src_path+"/stats/"
        self.log_name = self.log_dir+"/stats.log"
        self.log_name_low = self.log_dir+"/copy_low.log"
        self.log_name_med = self.log_dir+"/copy_medium.log"
        self.log_name_hig = self.log_dir+"/copy_high.log"
        self.log_name_exa = self.log_dir+"/copy_exact.log"
        self.log_list_pkl = self.log_dir+"/log_list.pkl"
Ejemplo n.º 9
0
 def get_timestamp(self,time):
     if time =='':
         return ''
     else:
         #now = datetime.datetime.now()
         t = time.isoformat("T", "milliseconds")
         return t + "Z"
Ejemplo n.º 10
0
    def test__datetimeToStr(self):
        time = datetime.datetime.now(datetime.timezone.utc)
        plant_data = self.samplePlantData(time)
        ApiMetricStorage.datetimeToStr(plant_data)
        expected_plant_data = self.samplePlantData(time.isoformat())

        self.assertDictEqual(plant_data, expected_plant_data)
Ejemplo n.º 11
0
def insert_query(data):
    statement = "SELECT deal_id FROM db_grad_cs_1917.deal ORDER BY deal_id DESC LIMIT 1"
    for result in cursor.execute(statement, multi=True):
        res = result.fetchone()
        id = str(res[0] + 1)

    time = data["time"]
    time = datetime.datetime.strptime(time, '%d-%b-%Y (%H:%M:%S.%f)')
    time = str(time.isoformat())

    statement = "SELECT counterparty_id FROM db_grad_cs_1917.counterparty WHERE counterparty_name='" + data[
        "cpty"] + "'"
    for result in cursor.execute(statement, multi=True):
        res = result.fetchone()
        counterparty = res[0]

    statement = "SELECT instrument_id FROM db_grad_cs_1917.instrument WHERE instrument_name='" + data[
        "instrumentName"] + "'"
    for result in cursor.execute(statement, multi=True):
        res = result.fetchone()
        instrument = res[0]

    deal_type = data["type"]
    amount = data["price"]
    quantity = data["quantity"]

    sql_insert = "Insert into db_grad_cs_1917.deal " \
                 "VALUES(" + id + ", '" + time + "', " + str(counterparty) + ", " + str(instrument) + ", '" + deal_type + "', " + str(round(amount, 2)) + ", " + str(quantity) +")"
    cursor.execute(sql_insert)
    connection.commit()
def isoformat(time):
    if isinstance(time, datetime.datetime):
        return time.isoformat()
    elif isinstance(time, datetime.timedelta):
        hours = time.seconds // 3600
        minutes = time.seconds % 3600 // 60
        seconds = time.seconds % 3600 % 60
        return 'P%sDT%sH%sM%sS' % (time.days, hours, minutes, seconds)
Ejemplo n.º 13
0
def get_emoji(token, id_num):
    emoji_time = {}
    graph = facebook.GraphAPI(access_token=token, version=2.7)
    post = graph.get_object(id='{}?fields=video_insights'.format(id_num))
    emoji_value = post['video_insights']['data'][-1]['values'][0]['value']
    time = datetime.datetime.now()
    emoji_time[time.isoformat(" ")] = emoji_value
    emoji_list.append(emoji_time)
Ejemplo n.º 14
0
def make_feature(vehicle, id):
    point = gj.Point(tuple(vehicle['location']['coordinates']))
    time = arrow.get(vehicle['timestamp']).to('America/Chicago')
    f = {
        'geometry': point,
        'properties': {'time': time.isoformat()},
        'id': id
    }
    return gj.Feature(**f)
Ejemplo n.º 15
0
def storeParameters(n_clicks, observer, datamode, readoutcard, framenumber):
    if readoutcard == 9:
        new_readoutcard = 'All'
    else:
        new_readoutcard = readoutcard
    time = datetime.datetime.utcnow()
    time = time.isoformat()
    parameters = [observer, datamode, new_readoutcard, framenumber, time]
    return json.dumps(parameters)
Ejemplo n.º 16
0
def TimeToText(time, config):
    try:
        try:
            time = time.time()
        except:
            pass
        return time.isoformat()
    except:
        return config.Read('/Wammu/DefaultTime')
Ejemplo n.º 17
0
def TimeToText(time, config):
    try:
        try:
            time = time.time()
        except:
            pass
        return time.isoformat()
    except:
        return config.Read('/Wammu/DefaultTime')
def getDate(timestamp): 
    '''helper funtion for sort() that uses datetime module'''
    '''returns the date in the form yyyy-mm-dd'''
    timeInfo = timestamp.split() # divides the timestamp values (strings) into a list
    yr = int(timeInfo[3])
    month = getMonth(timeInfo[2])
    day = int(timeInfo[1])
    time = datetime.date(yr,month,day)
    return time.isoformat() # this makes it return in the readable format
Ejemplo n.º 19
0
def getDate(timestamp): 
    '''Helper funtion for sort() that uses datetime module and
       returns the date in the form yyyy-mm-dd
       :param timestamp: string in the form of Mon, 26 Jan 2015 18:26:19 -0800 (PST)'''
    timeInfo = timestamp.split() # divides the timestamp values (strings) into a list
    yr = int(timeInfo[3])
    month = getMonth(timeInfo[2])
    day = int(timeInfo[1])
    time = datetime.date(yr,month,day)
    return time.isoformat() # this makes it return in the readable format
Ejemplo n.º 20
0
 def datetime_to_rfc(self, time_string, time):
     """_Validates user-inputted time and
     converts it to RFC 3339 time format to
     create a startTime or stopTime element
     """
     if type(time) is not datetime:
         raise TypeError("%s is not a valid %s" % (str(time), time_string))
     timeTag = etree.Element(time_string)
     timeTag.text = time.isoformat() + "Z"
     return timeTag
Ejemplo n.º 21
0
def error(err):

    try:
        source = "Ary News"
        time = datetime.datetime.now()
        time = time.isoformat()
        time = arrow.get(time).datetime
        collection3.insert([{"Error": err, "Source Name": source, "Time of Error": time, "Category": "National"}])
    except:
        pass
Ejemplo n.º 22
0
Archivo: store.py Proyecto: fl4p/tescan
 def write(self, measurement, time: datetime.datetime, tags, data):
     if not data:
         return False
     self.queue.put({
         "measurement": measurement,
         "tags": tags,
         "time": time.isoformat(),
         "fields": data,
     })
     return True
Ejemplo n.º 23
0
 def datetime_to_rfc(self, time_string, time):
     """_Validates user-inputted time and
     converts it to RFC 3339 time format to
     create a startTime or stopTime element
     """
     if type(time) is not datetime:
         raise TypeError("%s is not a valid %s" % (str(time), time_string))
     timeTag = etree.Element(time_string)
     timeTag.text = time.isoformat() + "Z"
     return timeTag
Ejemplo n.º 24
0
	def track_charge(self, amount, properties=None, time=None, *args, **kwargs):
		try:
			amount = float(amount)
		except:
			raise Exception, "Amount must be a number"
		props = {'$amount': amount}
		if time is not None:
			props['$time'] = time.isoformat()
		props.update(properties)
		return self.append('$transactions', value=props, *args, **kwargs)
Ejemplo n.º 25
0
def make_time_string(time=None):
    if time is None:
        time = datetime.utcnow()
    result = time.isoformat()
    if (len(result) < 23):
        if (len(result) == 19):
            result = result + ".000000"
        else:
            result = result + "000"
    result = result[:23] + "Z"
    return result
Ejemplo n.º 26
0
def aggregateMeasurements(sensors, time, day_count):
    for s in sensors:
        log('Aggregating data for %s at location %d...' %
            (s['data']['name'], s['data']['locationId']))
        # First, aggregate days...
        url = api + 'day-average/%d/%s/%d' % (s['id'], (
            time - timedelta(days=day_count)).isoformat(), day_count)
        getChecked(url)
        # Next, aggregate thirteen months.
        url = api + 'month-average/%d/%s/13' % (s['id'], time.isoformat())
        getChecked(url)
def touch_handler(addr, tags, stuff, source):
	add_source_to_list(get_device_name(stuff[0]),source)
	add_active_device(stuff[0])
	if (tags == "sfff"):
		time = datetime.now()
		message = [time.isoformat(),"touch",get_device_name(stuff[0]),stuff[1],stuff[2],stuff[3]]
		log_messages(message,live_messages)
		touch_messages.append([time,get_device_name(stuff[0]),stuff[1],stuff[2],stuff[3]])
		## Repeat Message to visualiser:
		if (VISUALISER_MODE_ON): 
			send_touch_to_visualiser(stuff)
def getTime(timestamp): 
    '''helper funtion for sort() that uses datetime module'''
    '''returns the time in the form hh:mm:ss'''
    timeInfo = timestamp.split() # divides the timestamp values (strings) into a list
    hms_string = timeInfo[4].split(':') # splits the time data into a list [h,m,s]
    hms = map(int,hms_string) # converts all hr, min, sec values to integers
    h = hms[0]
    m = hms[1]
    s = hms[2]
    time = datetime.time(h,m,s)
    return time.isoformat() # this makes it return in the readable format
Ejemplo n.º 29
0
def ReadSerie():
    try:
        ser = serial.Serial(serialPort, 9600, timeout=1)
    except Exception as e:
        # If there is a problem during the serial
        # connection
        time = datetime.datetime.now()
        string = time.isoformat(
        ) + " : Error, impossible to connect to the serial port\n" + str(e)
        logging.error(string)
        print("Error, impossible to connect to the serial port, exiting...")
        sys.exit(-2)
    result = ser.read(1024)
    ser.close()
    s = "DEFAULT"
    try:
        s = result.decode("utf-8")
    except Exception as e:
        time = datetime.datetime.now()
        string = time.isoformat(
        ) + " : Error, impossible to decode in UTF-8\n" + str(e)
        logging.error(string)
    if s == "TIMEOUT":
        # Create a log report
        print("Timeout for the receiver")
        time = datetime.datetime.now()
        string = time.isoformat() + " : Timeout on the receiver"
        logging.warning(string)
    elif s == "ERROR":
        # Create a log report
        time = datetime.datetime.now()
        print("Error during the transmission")
        string = time.isoformat() + " : Error during the transmission"
        logging.error(string)
    elif s == "DEFAULT":
        print("Default")
    elif s == '':
        print("Nothing received")
    else:
        print(s)
        mqttc.publish(topic, s, 0)
Ejemplo n.º 30
0
def make_system_point(cpu, mem, proc):
    points = []
    time = datetime.now() + timedelta(hours=7)
    measurments = ["cpu", "mem", "processes"]
    point = {}
    for measurement in measurments:
        if measurement == "cpu":
            point = {
                "measurement": measurement,
                "time": time.isoformat() + "Z",
                "fields": {
                    "usage_idle": float(cpu.get("usage_idle")),
                    "n_cpus": float(cpu.get("n_cpus")),
                    "n_threads": float(cpu.get("n_cpus")) * 2
                }
            }
        elif measurement == "mem":
            point = {
                "measurement": measurement,
                "time": time.isoformat() + "Z",
                "fields": {
                    "used":
                    float(mem.get("used")),
                    "total":
                    float(mem.get("total")),
                    "used_percent":
                    float(mem.get("used")) / float(mem.get("total")) * 100
                }
            }
        elif measurement == "processes":
            point = {
                "measurement": measurement,
                "time": time.isoformat() + "Z",
                "fields": {
                    "blocked": int(proc.get("blocked")),
                    "total": int(proc.get("total")),
                    "idle": int(proc.get("idle"))
                }
            }
        points.append(point)
    return points
Ejemplo n.º 31
0
def make_proc_point(procToMonitor):
    points = []
    time = datetime.now() + timedelta(hours=7)
    for proc, val in procToMonitor.items():
        point1 = {
            "measurement": "cpu",
            "time": time.isoformat() + "Z",
            "fields": {
                proc: val[0]
            }
        }
        point2 = {
            "measurement": "mem",
            "time": time.isoformat() + "Z",
            "fields": {
                proc: val[1]
            }
        }
        points.append(point1)
        points.append(point2)
    return points
Ejemplo n.º 32
0
    def datetime_to_rfc(self, time_string, time, namespace):

        if type(time) is not datetime:
            raise TypeError("%s is not a valid %s" % (str(time), time_string))
        timestr = time.isoformat()
        if len(timestr) == 19:
            timestr += "."
        while len(timestr) != 26:
            timestr += "0"
        timeTag = etree.Element(time_string, xmlns=namespace)
        timeTag.text = timestr + "Z"
        return timeTag
Ejemplo n.º 33
0
def new_diagnosis(doctor_id, patient_id, time, diag):
    data = {
        "doctor_id": doctor_id,
        "nucleic_acid": diag['dna'],
        "patient_id": patient_id,
        "symptom": diag['words'],
        "temperature": diag['temp'],
        "time": time.isoformat(),
    }
    res = s.post(api + "diagnosis/createDiagnosis", data=data)
    res = json.loads(res.text)['data']
    log(res, sender="DIAGNOSIS")
Ejemplo n.º 34
0
def get_presence_msg(action, data):
    time = datetime.datetime.now()
    msg = {
        "action": action,
        "time": time.isoformat(),
        "user": {
                "account_name":  "anonim",
                "status":      "Yep, I am here!"
        },
        "data": data
    }

    return jim.pack(msg)
Ejemplo n.º 35
0
def isoformat(time):
    '''
    将datetime或者timedelta对象转换成ISO 8601时间标准格式字符串
    :param time: 给定datetime或者timedelta
    :return: 根据ISO 8601时间标准格式进行输出
    '''
    if isinstance(time, datetime.datetime): # 如果输入是datetime
        return time.isoformat();
    elif isinstance(time, datetime.timedelta): # 如果输入时timedelta,计算其代表的时分秒
        hours = time.seconds // 3600
        minutes = time.seconds % 3600 // 60
        seconds = time.seconds % 3600 % 60
    return 'P%sDT%sH%sM%sS' % (time.days, hours, minutes, seconds) # 将字符串进行连接
Ejemplo n.º 36
0
    async def set_date_time(self,
                            date: datetime.date = None,
                            time: datetime.time = None):
        """Set the spa date, time, or both
        """

        assert date is not None or time is not None
        config = {}
        if date is not None:
            config['date'] = date.isoformat()
        if time is not None:
            config['time'] = time.isoformat('minutes')
        body = {'dateTimeConfig': config}
        await self.request('POST', body)
Ejemplo n.º 37
0
def make_point(service, status, sub):
    points = []
    time = datetime.now() + timedelta(hours=7)
    point = {
        "measurement": "service",
        "time": time.isoformat() + "Z",
        "fields": {
            "name": service,
            "status": status,
            "sub": sub
        }
    }
    points.append(point)
    return points
Ejemplo n.º 38
0
    def main():
        pacote = []
        i = 0
        for i in range(1):
            idradar = random.randrange(0, 10)
            camera = random.randrange(0, 2)
            raspberry = random.randrange(0, 2)
            usrp = random.randrange(0, 2)
            func_geral = random.randrange(0, 2)
            time = datetime.datetime.utcnow()
            time = str(time.isoformat('T') + 'Z')
            with open("21:45:1:884238.jpg", "rb") as file:
                img1 = base64.b64encode(file.read())
            with open("21:45:1:884238.jpg", "rb") as file:
                img2 = base64.b64encode(file.read())

            lista = controle_infra()
            vm = lista[0]
            vc = lista[1]
            infracao = lista[2]
            penalidade = lista[3]
            vr = lista[4]

            base = {
                "type": "dados_carro",
                "payload": {
                    "id_radar": idradar,
                    "infracao": infracao,
                    "imagem1": img1,
                    "imagem2": img2,
                    "velocidade_medida": vm,
                    "velocidade_considerada": vc,
                    "velocidade_regulamentada": vr,
                    "penalidade": penalidade,
                    "date": time,
                    "camera": camera,
                    "raspberry": raspberry,
                    "usrp": usrp,
                    "func_geral": func_geral
                }
            }

            pacote.append(base)
            base = {}

        save_file(pacote)
        x = send_file(url)
        print('Codigo de Estado:', x)
def log_gestures(classes, log):
	if not classes:
		return
	time = datetime.now()
	## First add to the file log.
	message_log_line = [time.isoformat()]
	message_log_line.append("/classifier/gestures")
	for key in classes.keys():
		message_log_line.append(key)
		message_log_line.append(classes[key])
	log_messages(message_log_line,live_messages)
	
	## Now add to the gesture log.
	classes = [classes[n] for n in classes.keys()]
	classes.insert(0,time)
	log.append(classes)
Ejemplo n.º 40
0
    def test__PonyMetricStorage_insertPlantData__storeTemperatureSensorWithoutTemperature(
            self):
        sensor_name = 'Alice'
        plant_name = 'SomEnergia_Alibaba'
        time = datetime.datetime.now(datetime.timezone.utc)

        with orm.db_session:
            alcolea = self.pony.db.Plant(name=plant_name,
                                         codename='SOMSC01',
                                         description='descripción de planta')
            sensor = self.pony.db.SensorTemperatureAmbient(name=sensor_name,
                                                           plant=alcolea)
            orm.flush()
            plant_data = {
                "plant":
                plant_name,
                "version":
                "1.0",
                "time":
                time.isoformat(),  #consider using fastapi.jsonable_encoder
                "devices": [{
                    "id":
                    "SensorTemperatureAmbient:Alice",
                    "readings": [{
                        "temperature_dc": None,
                        "time": time,
                    }]
                }]
            }
            self.storage.insertPlantData(plant_data)
            orm.flush()

            expected_plant_data = {
                'plant':
                plant_name,
                'devices': [{
                    'id':
                    'SensorTemperatureAmbient:Alice',
                    'readings': [{
                        "temperature_dc": None,
                        "time": time,
                    }]
                }],
            }

            self.assertDictEqual(self.storage.plantData(plant_name),
                                 expected_plant_data)
Ejemplo n.º 41
0
    def getNextEvent(self, skipMins=0):
        log.debug("Fetching details of next event")
        if not self.checkCredentials():
            raise Exception("GCal credentials not authorized")

        time = datetime.datetime.now()
        time += datetime.timedelta(
            minutes=skipMins
        )  # In case we want to ignore events in a certain time

        result = self.service.events().list(calendarId=Credentials.CALENDAR,
                                            maxResults='1',
                                            orderBy='startTime',
                                            singleEvents='true',
                                            timeMin="%sZ" %
                                            (time.isoformat())).execute()

        events = result.get('items', [])
        return events[0]
Ejemplo n.º 42
0
def timeformat(time, base_time, verbosity):
    if verbosity == 0:
        if time > base_time:
            return "in " + humanize.naturaldelta(time - base_time)
        else:
            return humanize.naturaltime(time) + "ago"

    if verbosity == 1:
        if time > base_time:
            return "in " + humanize.precisedelta(
                time - base_time, minimum_unit="seconds", format="%0.0f")
        else:
            return humanize.precisedelta(base_time - time,
                                         minimum_unit="seconds",
                                         format="%0.0f") + "ago"
    if verbosity == 2:
        return time.replace(microsecond=0).isoformat(sep=' ')
    if verbosity >= 3:
        return time.isoformat(sep=' ')
Ejemplo n.º 43
0
 def __call__(self, time):
     """Scrub to a point in the experiment replay, given by time
     which is a datetime object."""
     if self.experiment._replay_time_index > time:
         self.experiment.revert_to_time(session=self.session, target=time)
     events = self.experiment.events_for_replay(session=self.session,
                                                target=time)
     for event in events:
         if event.creation_time <= self.experiment._replay_time_index:
             # Skip events we've already handled
             continue
         if event.creation_time > time:
             # Stop once we get future events
             break
         self.experiment.replay_event(event)
         self.experiment._replay_time_index = event.creation_time
     # Override app_id to allow exports to be created that don't
     # overwrite the original dataset
     self.experiment.app_id = "{}_{}".format(
         self.experiment.original_app_id, time.isoformat())
Ejemplo n.º 44
0
    def start_scan(self, isCal=False):
        if self.settings.mode == Mode.SINGLE:
            if self.save_warn(Warn.SCAN):
                return False

        if not self.threadScan:
            self.set_control_state(False)
            samples = calc_samples(self.settings.dwell)
            self.status.set_info("")
            self.scanInfo.setFromSettings(self.settings)
            time = datetime.datetime.utcnow().replace(microsecond=0)
            self.scanInfo.time = time.isoformat() + "Z"
            self.scanInfo.lat = None
            self.scanInfo.lon = None
            self.scanInfo.desc = ""
            self.stopAtEnd = False
            self.stopScan = False
            self.threadScan = ThreadScan(self, self.sdr, self.settings, self.settings.index, samples, isCal)
            self.filename = "Scan {0:.1f}-{1:.1f}MHz".format(self.settings.start, self.settings.stop)
            self.graph.set_plot_title()
            return True
def append_songs(db, url):
	connection = dbapi2.connect(db)
	c = connection.cursor()

	thisdate = datetime.date.today()

	c.execute('select next_id from last_parsed order by id desc limit 1');
	nextAt = c.fetchone()
	if (nextAt):
		nextAt = nextAt[0]
	else:
		nextAt = 1
	url = url + '/ev/' + str(nextAt)
	url = url + '?tos=http://www.iangreenleaf.com/TermsOfService'

	page = urllib.urlopen(url)
	result = simplejson.load(page)

	count = 0
	for song in recent_songs(result):
			dt = song[0]
			date = dt.date()
			time = dt.time()
			artist = song[1]
			title = song[2]
			c.execute('insert into songs\
					(date_played, time_played, artist, title)\
					values (?, ?, ?, ?)', (date.isoformat(), time.isoformat(), artist, title))
			count = count + 1

	next_id = result['next']
	c.execute('insert into last_parsed (next_id, date, count)\
			values (?, ?, ?)', (next_id, thisdate.isoformat(), count))

	connection.commit()
	c.close()

	return
Ejemplo n.º 46
0
def print_message_with_time(message, time=datetime.datetime.now()):
    print("%s : %s" % (time.isoformat(), message))
Ejemplo n.º 47
0
Archivo: update.py Proyecto: cypok/qttt
 def sqlTimeFormat(time):
     return time.isoformat() if time else None
Ejemplo n.º 48
0
 def set_updated(self, time) :
   """Sets the updated time as a datetime object."""
   self.set_element_text('updated', time.isoformat())