def send(raw): key = raw['branchId'] key += raw['contractName'] key += raw['trplIdList'] if raw['countFields'] == '4': key += raw['serviceList'] value = raw['response'] ttl = calendar.timegm(datetime.timetuple(raw['LifeTime'])) expired = calendar.timegm(datetime.timetuple(raw['ExpireTime'])) print key, ttl, expired data = { 'space': 'servicesProfile', '1': key, '2': value, '3': ttl, '4': expired } json_string = json.dumps(data) headers = {'Content-Type': "application/json"} req = urllib2.Request(url, json_string, headers) try: response = urllib2.urlopen(req) if response.code == 200: print key, 'saved' except urllib2.HTTPError as e: print key, 'not saved'
def painthms(self): #T = datetime.timetuple(datetime.utcnow()-self.delta) if self.togstate == 0: T = datetime.timetuple(self.oldtime) else: self.newtime=self.oldtime+self.tdelta self.oldtime=self.newtime T = datetime.timetuple(self.newtime) x,x,x,h,m,s,x,x,x = T self.root.title('%02i:%02i:%02i' %(h,m,s)) angle = -pi/2 + (pi/6)*h + (pi/6)*(m/60.0) x, y = cos(angle)*.60,sin(angle)*.60 scl = self.canvas.create_line scl(apply(self.T.twopoints,[0,0,x,y]), fill = self.timecolor, tag =self._ALL, width = 6) angle = -pi/2 + (pi/30)*m + (pi/30)*(s/60.0) x, y = cos(angle)*.80,sin(angle)*.80 scl(apply(self.T.twopoints,[0,0,x,y]), fill = self.timecolor, tag =self._ALL, width = 3) angle = -pi/2 + (pi/30)*s x, y = cos(angle)*.95,sin(angle)*.95 scl(apply(self.T.twopoints, [0,0,x,y]), fill = self.timecolor, tag =self._ALL, arrow = 'last')
def get_series(self, node_id, metric_id, npoints, start = None, end = None, key = None): url = "/nodes/%x/series/%x" % (node_id, metric_id) args = { 'npoints' : npoints } # Convert start/end to UNIX timestamp if start: args['start'] = time.mktime(datetime.timetuple(start)) if end: args['end'] = time.mktime(datetime.timetuple(end)) (status, series) = self.__do_request('GET', url, args = args, key = key) return series
def argv_count(numb, sec): sec = int(sec) numb = int(numb) start = datetime.now() for x in count(numb): stop = datetime.now() if (int(strftime("%S", datetime.timetuple(stop))) - int(strftime("%S", datetime.timetuple(start)))) < sec: print(x) sleep(1) else: break
def argv_cycle(sec, *args): sec = int(sec) start = datetime.now() print(args) for x in cycle(args): stop = datetime.now() if (int(strftime("%S", datetime.timetuple(stop))) - int(strftime("%S", datetime.timetuple(start)))) < sec: print(x) sleep(1) else: break
def before_request(): global sys_weblog sys_weblog = {} sys_weblog['user'] = current_user sys_weblog['log'] = {} st = datetime.utcnow() sys_weblog['log']['request_id'] = "{}{}".format(time.mktime(datetime.timetuple(st)),randint(1, 1000000)) sys_weblog['log']['st'] = time.mktime(datetime.timetuple(st))*1000 + st.microsecond/1000 sys_weblog['log']['ip'] = request.remote_addr sys_weblog['log']['url'] = request.url g.request_id = sys_weblog['log']['request_id'] if not sys_weblog['user'].is_anonymous: sys_weblog['user']['user_id'] = g.user.id
def destination(request, number): request.session['tid'] = number t22 = travel.objects.get(id=number) request.session['tname'] = t22.destination request.session['tdescription'] = t22.description time1 = t22.start_date time1 = datetime.timetuple(time1) request.session['tstart'] = str(strftime("%Y %m %d ", time1)) time2 = t22.end_date time2 = datetime.timetuple(time2) request.session['tend'] = str(strftime("%Y %m %d ", time2)) return redirect('/dsuc')
def dateTimeCountMapper(doc): from dateutil.parser import parse from datetime import datetime as dt if doc.get("Date"): _date = list(dt.timetuple(parse(doc["Date"]))[:-3]) yield (_date, 1)
def query(self, host, port, dbname, query): try: c = MongoConnection(host=host, port=int(port), pool_size=1) db = database.Database(c, dbname) if not query.startswith('db.'): return -2 res = eval(query) if isinstance(res, (GeneratorType, ListType, Cursor)): entries = [] try: for r in res: tmp = {} for k, v in r.items(): if isinstance(v, datetime): tmp[k] = strftime('%Y-%m-%d %X', datetime.timetuple(v)) else: tmp[k] = v entries.append(tmp) return {'count':len(entries), 'entries': entries} except: return str(res) else: return str(res) except Exception, err: return -1
def create1(self): self.canvas.delete(ALL) year, month, date, *extra = datetime.timetuple(datetime.utcnow() - self.time_gap) month_list = [ 'Jan', 'Febr', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ] month_name = month_list[month - 1] start, step = pi / 2, pi / 6 for i in range(12): angle = start - (i * step) x_coord, y_coord = cos(angle), sin(angle) if i == month or (i + 12) == month: self.canvas.create_text(self.convert.change(x_coord, y_coord), fill='red', text=' '.join( [str(date), month_name, str(year)]), font='Harrington 15') elif i == 0: self.canvas.create_text(self.convert.change(x_coord, y_coord), fill='blue', text=str(12), font=self.font_digital) else: self.canvas.create_text(self.convert.change(x_coord, y_coord), fill='blue', text=str(i), font=self.font_digital) self.create_needles() self.create_circle(0, 0)
def collect(self, config): data = self.new_data() agent = Agent(reactor) headers = { "User-Agent": ["Mozilla/3.0Gold"], } for datasource in config.datasources: try: url = 'https://api.weather.gov/alerts/active?zone={query}'.format( query=datasource.params['county']) response = yield agent.request('GET', url, Headers(headers)) response_body = yield readBody(response) response_body = json.loads(response_body) except Exception: LOG.exception('%s: failed to get alerts data for %s', config.id, datasource.params['station_name']) continue for rawAlert in response_body.get('features'): alert = rawAlert['properties'] # severity = None expires = parser.parse(alert['expires']) if datetime.timetuple(expires) <= time.gmtime(): severity = 0 elif alert['certainty'] == 'Likely': severity = 4 else: severity = 3 data['events'].append({ 'device': config.id, 'component': datasource.component, 'severity': severity, 'eventKey': 'nws-alert-{}'.format(alert['event'].replace(' ', '')), 'eventClassKey': 'nws-alert', 'summary': alert['headline'], 'message': alert['description'], 'nws-sender': alert['senderName'], 'nws-date': alert['effective'], 'nws-expires': alert['expires'], 'nws-category': alert['category'], 'nws-instruction': alert['instruction'], 'nws-type': alert['event'], }) returnValue(data)
def Create_Day_Dial(self): year, month, date, h, m, s, day, yday, *extra = datetime.timetuple( datetime.utcnow() - self.time_gap) day = day + 1 ####### start, step = pi / 2, pi * 2 / 7 for i in range(7): angle = start - (i * step) x_coord, y_coord = 0.2 * cos(angle), 0.2 * sin(angle) self.canvas.create_text(self.convert.change( x_coord - 0.5, y_coord), fill='blue', text=str(i + 1), font='calibri 9') angle = start - ((day - 1) * step) x_day, y_day = 0.15 * cos(angle), 0.15 * sin(angle) day_list = [ 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY' ] day_name = day_list[day - 1] self.canvas.create_text(self.convert.change(0.5, 0), fill='white', text=day_name, font='Papyrus 10') self.canvas.create_line(self.convert.coords(-0.5, 0, x_day - 0.5, y_day), fill="red", width=3) self.canvas.create_text(self.convert.change(-0.5, 0.05), fill='white', text='Day', font='Papyrus 10')
def dateTimeToDocMapper(doc): from dateutil.parser import parse from datetime import datetime as dt if doc.get('created_at'): # [year, month, day, hour, min, sec] _date = list(dt.timetuple(parse(doc['created_at']))[:-3]) yield (_date, doc)
def datetime_to_milliseconds(datetime): try: time_in_millisec = mktime(datetime.timetuple()) * 1000 return int(time_in_millisec) except Exception as errorTrace: print errorTrace return 0
def create(self): self.canvas.delete(ALL) year, month, date, hrs, min, sec, *extra = datetime.timetuple( datetime.utcnow() - self.time_gap) month_list = [ 'Jan', 'Febr', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ] month_name = month_list[month - 1] start, step = pi / 2, pi / 6 for i in range(12): angle = start - (i * step) x_coord, y_coord = cos(angle), sin(angle) if i == month or (i + 12) == month: self.create_circle(x_coord, y_coord, True) self.canvas.create_text( self.convert.change(x_coord, y_coord - 2 * self.circle_size), fill="white", text=' '.join([str(date), month_name, str(year)]), font='Calibri 10') else: self.create_circle(x_coord, y_coord) self.create_needles() self.create_circle(0, 0)
def update_cve_db(): print 'Updating vulnerability information...' for idx, metadata in enumerate(metalist): r = requests.get(metadata) regex_last_mod = re.compile(r'lastModifiedDate:(.*)') updated = regex_last_mod.findall(r.text) updated = updated[0].strip('\t\r\n') datetime = dateutil.parser.parse(updated) updatedepoch = int(time.mktime(datetime.timetuple())) feed_tmp = dllist[idx].split('.xml.gz')[0] feed = feed_tmp.split( 'https://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-')[-1] dllink = dllist[idx] results = c.execute( '''SELECT last_download FROM download_dates WHERE link = ?''', (dllink, )) result = results.fetchall() if result: last_download = int(result[0][0]) if last_download < updatedepoch: import_download_date(dllink, updatedepoch) import_cves(dllink) else: print str(datetime.now()).split( '.')[0] + "\t" + feed + "\t" + "Already up-to-date." else: import_download_date(dllink, updatedepoch) import_cves(dllink)
def painthms(self): self.canvas.delete(self._ALL) # delete the handles T = datetime.timetuple(datetime.utcnow() - self.delta) x, x, x, h, m, s, x, x, x = T self.root.title('%02i:%02i:%02i' % (h, m, s)) angle = pi / 2 - pi / 6 * (h + m / 60.0) x, y = cos(angle) * 0.70, sin(angle) * 0.70 scl = self.canvas.create_line # draw the hour handle scl(self.T.windowToViewport(0, 0, x, y), fill=self.timecolor, tag=self._ALL, width=self.pad / 3) angle = pi / 2 - pi / 30 * (m + s / 60.0) x, y = cos(angle) * 0.90, sin(angle) * 0.90 # draw the minute handle scl(self.T.windowToViewport(0, 0, x, y), fill=self.timecolor, tag=self._ALL, width=self.pad / 5) angle = pi / 2 - pi / 30 * s x, y = cos(angle) * 0.95, sin(angle) * 0.95 # draw the second handle scl(self.T.windowToViewport(0, 0, x, y), fill=self.timecolor, tag=self._ALL, arrow='last')
def query(self, host, port, dbname, query): try: c = MongoConnection(host=host, port=int(port), pool_size=1) db = database.Database(c, dbname) if not query.startswith('db.'): return -2 res = eval(query) if isinstance(res, (GeneratorType, ListType, Cursor)): entries = [] try: for r in res: tmp = {} for k, v in r.items(): if isinstance(v, datetime): tmp[k] = strftime('%Y-%m-%d %X', datetime.timetuple(v)) else: tmp[k] = v entries.append(tmp) return {'count': len(entries), 'entries': entries} except: return str(res) else: return str(res) except Exception, err: return -1
def viento_historico(request, id_estacion = 1): try: station = Station.objects.get(pk=id_estacion) except Station.DoesNotExist: response_data = {} response_data['status'] = 'error' response_data['message'] = 'No existe la estacion indicada' return HttpResponse(json.dumps(response_data), content_type="application/json") desde = request.GET.get('desde', datetime.today().strftime("%Y-%m-%d")) desde = datetime.strptime(desde, '%Y-%m-%d') desde = desde.replace(hour=00, minute=01) pprint.pprint(desde) fechaHastaDefault = datetime.today() - timedelta(days=10) hasta = request.GET.get('hasta', fechaHastaDefault.strftime("%Y-%m-%d")) hasta = datetime.strptime(hasta, '%Y-%m-%d') hasta = hasta.replace(hour=23, minute=59) pprint.pprint(hasta) # forzar a que sea una lista el resultado para poder serializar - https://docs.djangoproject.com/en/dev/ref/models/querysets/ datos = list(Data.objects.filter(~Q(windspeed=None), station = station, datetime__gt = desde, datetime__lt = hasta)) result = [] for d in datos: result.append({'pk' : d.pk, 'datetime' : calendar.timegm(datetime.timetuple(d.datetime)) * 1000, 'windspeed' : d.windspeed_kmh}) response_data = {} response_data['status'] = 'ok' response_data['data'] = result return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type="application/json")
def get_unix_time(datetime): """ :param datetime: :return: """ return int(time.mktime(datetime.timetuple()))
def create_needles(self): year, month, date, hrs, min, sec, *extra = datetime.timetuple( datetime.utcnow() - self.time_gap) angle = (pi / 2) - (pi / 6) * (hrs + (min / 60.0)) x_hrs, y_hrs = cos(angle) * self.len_hrs, sin(angle) * self.len_hrs angle = (pi / 2) - (pi / 30) * (min + (sec / 60.0)) x_min, y_min = cos(angle) * self.len_min, sin(angle) * self.len_min angle = (pi / 2) - (pi / 30) * sec x_sec, y_sec = cos(angle) * self.len_sec, sin(angle) * self.len_sec month_list = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] month_name = month_list[month - 1] time_display = '%02i : %02i : %02i' % (hrs, min, sec) date_display = ' '.join([str(date), month_name, str(year)]) digital_time = time_display + "\n" + date_display draw_line = self.canvas.create_line self.root.title(time_display) draw_line(self.convert.coords(0, 0, x_hrs, y_hrs), fill=self.needle_color, width=self.width_hrs) draw_line(self.convert.coords(0, 0, x_min, y_min), fill=self.needle_color, width=self.width_min) draw_line(self.convert.coords(0, 0, x_sec, y_sec), fill=self.needle_color, arrow='last') self.canvas.create_text(self.convert.change(0, -1.4), fill=self.text_color, text=" " + digital_time, font=self.font_digital)
def identity_check(request): # 判断用户是否是本人 # 是否需要检测 if global_info.account_auth: try: return request.session['authenticated'] except: pass try: # 认证通过 d = datetime.utcnow() t = mktime(datetime.timetuple(d)) assert float(t) - float(request.session['timeStamp']) < 3600.0 assert hash_identity_coder.verify( request.session['Sid'] + request.session['timeStamp'], request.session['Secret']) is True request.session['authenticated'] = True return True except: return False else: return True
def parse_event_page(soup): event_dic = {} # extract initial details hw_divs = soup.find_all( 'div', attrs={"class": "description card-block calendar_event_due"}) open_quiz_divs = soup.find_all( 'div', attrs={"class": "description card-block calendar_event_open"}) assignments_links = [ x.find_all('a')[0]['href'] for x in (hw_divs + open_quiz_divs) ] for link in assignments_links: if 'moodle' not in link: continue html = export_html(link) due_time = None if 'quiz' in link: ps = html.find_all('p') for p in ps: if 'This quiz will close' in p.text: close_lst = p.text.split(',') close_str = close_lst[1] + close_lst[2] due_time = datetime.strptime(close_str, ' %d %B %Y %I:%M %p') break else: potential_dates_tags = html.find_all( 'td', attrs={"class": "cell c1 lastcol"}) for tag in potential_dates_tags: try: due_time = datetime.strptime(tag.text, '%A, %d %B %Y, %I:%M %p') break except ValueError: pass m = re.search("id=([0-9]*)", link) ex_id = m.group(1) course_name = html.find_all('h1')[0].text ex_name = html.find_all('h2')[0].text if due_time is None: logging.error("No due time " + link) continue time_stamp = mktime(datetime.timetuple(due_time)) event_dic[ex_id] = event.Event(ex_id, course_name, ex_name, time_stamp, link) return event_dic
def get_series(self, node_id, metric_id, npoints, start=None, end=None, key=None): url = "/nodes/%x/series/%x" % (node_id, metric_id) args = {'npoints': npoints} # Convert start/end to UNIX timestamp if start: args['start'] = time.mktime(datetime.timetuple(start)) if end: args['end'] = time.mktime(datetime.timetuple(end)) (status, series) = self.__do_request('GET', url, args=args, key=key) return series
def _encode(self, obj, ctx): unix_time = int(mktime(datetime.timetuple())) if unix_time == 0: return unix_time windows_time = unix_time + 11644473600 windows_time = windows_time * 10000000 return windows_time
def sinceDateMapper(doc): from dateutil.parser import parse from datetime import datetime as dt _date = list( dt.timetuple( parse(('{0[1]} {0[2]} {0[3]} {0[4]}'.format( doc['created_at'].split(' ')))[:-3]))) yield (_date, doc)
def run(self): prefetchDir = "C:/Windows/Prefetch/" unwanted = ["LOGONUI.EXE-09140401.pf", "NTOSBOOT-B00DFAAD.pf"] averageWaitMins = 4 # Load prefetch filenames into dictionary files = {} for filename in os.listdir(prefetchDir): if filename[-3:] == ".pf" and not filename in unwanted: files[filename] = 0 # populate dictionary with prefetch file execution counts totalExecutions = 0 for filename in files: f = open(prefetchDir + filename, 'rb') f.seek(152) count = f.read(4) files[filename] = self.bytesToNumber(count) # files only ever run once are probably useless for us, so set as 0 so they're never simulated if files[filename] == 1: files[filename] = 0 else: totalExecutions += files[filename] f.close() # loop, occasionally incrementing a file counter while 1: # generate a random prefetch file, weighted by number of executions countdown = random.randint(0, totalExecutions) for filename in files: if countdown <= files[filename]: break countdown -= files[filename] files[filename] += 1 totalExecutions += 1 # open the prefetch file, write out the current date/time minus 10 seconds and update the execution counter f = open(prefetchDir + filename, 'r+b') f.seek(128) f.write( self.numberToBytes( self.timeToFiletime( datetime.timetuple(datetime.now() - timedelta(seconds=10))), 8)) f.seek(152) for byte in range(0, 4): f.write(chr(int(files[filename] / (256**byte)) % 256)) f.close() try: time.sleep( random.randint(0, averageWaitMins * 60) + random.randint(0, averageWaitMins * 60)) except: return
def send_usd_rate_to_user(message): # отправляем пользователю сообщение с курсами 3 криптовалют time_marker = datetime.timetuple(datetime.now()) year = str(time_marker.tm_year) month = str(time_marker.tm_mon) day = str(time_marker.tm_mday) bot.send_message(message.chat.id, "Текущий курс доллара ЦБР на дату:\n{}.{}.{}".format(day, month, year)) bot.send_message(message.chat.id, f"{get_usd_rate()}")
def send_prices_to_user(message): # отправляем пользователю сообщение с курсами 3 криптовалют time_marker = datetime.timetuple(datetime.now()) year = str(time_marker.tm_year) month = str(time_marker.tm_mon) day = str(time_marker.tm_mday) bot.send_message(message.chat.id, "Текущий курс криптовалют биржи EXMO.COM дату:\n{}.{}.{}".format(day, month, year)) bot.send_message(message.chat.id, crypto.get_prices())
def submit_values(self, node_id, values, timestamp = None, key = None): req = { 'values' : values } if timestamp: # Convert timestamp from datetime to UNIX timestamp in ms jstime = time.mktime(datetime.timetuple(timestamp)) * 1000.0 req['timestamp'] = jstime # Submit without following the returned redirection - it's a waste of time (status, resp) = self.__do_request('POST', "/nodes/%x/values" % (node_id), req, key = key, redirect = False) return (status, resp)
def create_welcome_message(): now_hour = datetime.timetuple(datetime.now())[3] if now_hour in range(4, 13): welcome_message = 'Доброе утро' elif now_hour in range(14, 18): welcome_message = 'Добрый день' else: welcome_message = 'Добрый вечер' return welcome_message
def get_current_day(): now = dt.utcnow() current_dt = dt(now.year, now.month, now.day) current_timestamp = ( time.mktime(dt.timetuple(current_dt))) return int(current_timestamp * 1000)
def __get_time_offset(self, tweets): """Returns the min time offset between current time and a set of tweets.""" FROM = '%a %b %d %H:%M:%S +0000 %Y' now_ts = time.time() offset = lambda x: now_ts - time.mktime( dt.timetuple(dt.strptime(x['created_at'], FROM))) timeset = map(offset, tweets) return min(timeset)
def test_conversions( self ) : """Testing date format conversions""" log.info( "Testing date format conversions" ) utctz = timezone( 'UTC' ) timelist = list( datetime.timetuple( datetime.utcnow() ) )[:7] utcdt = choice([ datetime( *timelist ), utctz.localize( datetime( *timelist )) ]) for usertz in pytz.all_timezones : yield self._test_execute, utcdt, choice([ usertz, timezone( usertz ) ])
def doy(year=None, month=None, day=None): '''Calculate serial day of year ''' from datetime import date if day is not None and month is not None and year is not None: dt = date(year, month, day) return dt.timetuple().tm_yday else: return date.today().timetuple().tm_yday
def index(req,username,passwd,pid,lang,upload): if type(upload) == type(" "): ERROR = "Path specified doesn't point to a valid file." else: verdict = 0 count = 1 ERROR = "ERROR: Our server is facing some problem, please retry after few minutes." conn = DB.connect(host=MYSQL_HOST,passwd=MYSQL_PASS,user=MYSQL_USER,db=MYSQL_DB) cursor = conn.cursor() try: cursor.execute("""select password from user where username=%s""",(username,)) record = cursor.fetchone() if not record: ERROR = "Sorry, no username is registered with this name." verdict = 1 except: pass if verdict == 0: if passwd != record[0]: ERROR = "Wrong password." verdict = 1 try: cursor.execute("""select count,time from submission where problemid=%s and username=%sorder by count desc""",(str(pid),username)) record = cursor.fetchone() if record: subAll = MAX_SUBMISSION[ PROBLEMS_ID.index(pid) ] if record[0] == subAll: verdict = 1 ERROR = "You have already used all your chances for "+pid if datetime.timetuple(record[1]+timedelta(seconds=TIME_DIFF)) > localtime(): verdict = 1 ERROR = "Minimum gap between submissions for same problem is "+str(TIME_DIFF)+" secs, please wait" count = record[0]+1 except: return "ERROR" if verdict == 0: try: cursor.execute("""insert into submission(username,problemid,language,count,program) values(%s,%s,%s,%s,%s)""",(username,pid,lang,count,upload.value)) cursor.close() conn.commit() conn.close() ##exec("python ../eval/worker.py") return util.redirect(req,"status.py") except: pass cursor.close() conn.commit() conn.close() probList = "" for i in PROBLEMS_ID: probList+="<option value=\"%s\">%s</option>"%(i,i) langList = "" for i,j in zip(LANGUAGES,LANG_NICK): langList+="<option value=\"%s\">%s</option>"%(j,i) f = open(SYS_ROOT+"submission.html").read() return f % ("<h2>"+str(ERROR)+"</h2>",probList,langList)
def paintlight(self): # size the clock size = 0.9 # lat = 38.54040 lng = -121.73917 tz = -7 - 1 sunrise, sunset = sun.sunCalc(lat, lng, tz) while sunrise > 24.: sunrise -= 24. while sunset > 24.: sunset -= 24. lengthOfDay = sunset - sunrise daySize = lengthOfDay * (pi / 12.) nightSize = 2 * pi - daySize print("sunrise: " + str(sunrise)) print("sunset: " + str(sunset)) print("length of day: " + str(lengthOfDay)) riseAngle = pi / 2. - (pi / 12.) * sunrise setAngle = pi / 2. - (pi / 12.) * sunset while riseAngle < 0: riseAngle += 2 * pi while setAngle < 0: setAngle += 2 * pi print("rise angle: " + str(riseAngle)) print("set angle: " + str(setAngle)) print("") #daySize = np.absolute(riseAngle-setAngle) ############################################################ # determine if it is daytime or nightttime # T = datetime.timetuple(datetime.utcnow() - self.delta) # x, x, x, h, m, s, x, x, x = T # self.root.title('%02i:%02i:%02i' % (h, m, s)) # angle = pi / 2. - pi / 12. * (h + m / 60.0) # pi/12 is one hour # if (angle > riseAngle) and (angle < setAngle): # self.daytime = True # else: # self.daytime = False # ############################################################ arc = self.canvas.create_arc # night arc(self.T.windowToViewport(-size, -size, size, size), start=(riseAngle * 180. / pi), extent=(nightSize * 180. / pi), fill="navy", tag=self._ALL) # day arc(self.T.windowToViewport(-size, -size, size, size), start=(setAngle * 180. / pi), extent=(daySize * 180. / pi), fill="sky blue", tag=self._ALL)
def get_values(self, node_id, timestamp = None, key = None): if timestamp: unixtime = time.mktime(datetime.timetuple(timestamp)) (status, resp) = self.__do_request('GET', "/nodes/%x/values/%d" % (node_id, unixtime), key = key) else: # Get latest - server will redirect us (status, resp) = self.__do_request('GET', "/nodes/%x/values" % (node_id), key = key) # Convert returned timestamp from JS UNIX time into Python datetime ts = datetime.fromtimestamp(resp['timestamp'] / 1000.0) return (ts, resp['values'])
def get_midnighters(records): midnighters = [] for record in records: time = datetime.fromtimestamp(record['timestamp'], timezone(record['timezone'])) hour = datetime.timetuple(time)[3] if hour in range(START_NIGHT, END_NIGHT) and\ record['username'] not in midnighters: midnighters.append(record['username']) return midnighters
def dateTimeToDocMapper(doc): # Note that you need to include imports used by your mapper # inside the function definition from dateutil.parser import parse from datetime import datetime as dt if doc.get('Date'): # [year, month, day, hour, min, sec] _date = list(dt.timetuple(parse(doc['Date']))[:-3]) yield (_date, doc)
def dateTimeCountMapper(doc): from dateutil.parser import parse from datetime import datetime as dt if doc.get('Date'): try: _doc = str(doc.get('Date')).replace('[', '(').replace(']', ')') _date = list(dt.timetuple(parse(_doc[:-3]))) yield (_date, 1) except Exception as e: with open("/Users/cpence/projects/divorce/snitch/data/mbox.couchdb.log", mode='a') as f: f.write('\n\nException message: %s \n\n\t\tCurrent Document: %s' % (e.message, doc))
def http_date (datetime): try: tup = datetime.timetuple() when = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')[tup.tm_wday] when += ', %02d ' % tup.tm_mday when += ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[tup.tm_mon - 1] when += ' %04d %02d:%02d:%02d GMT' % ( tup.tm_year, tup.tm_hour, tup.tm_min, tup.tm_sec) return when except: return None
def POST(self): form = self.submit_form() if not form.validates(): return render.submit(app_header, form, app_footer) else: username = form["username"].value problem = form["problem"].value language = form["language"].value code = form["code"].value count = 1 try: conn = DB.connect(host=MYSQL_HOST, passwd=MYSQL_PASS, user=MYSQL_USER, db=MYSQL_DB) cursor = conn.cursor() cursor.execute( """select count, time from submission where problemid=%s and username=%s order by count desc""", (str(problem), username), ) subTuple = cursor.fetchone() flag = 0 if subTuple: problem_max_submission = MAX_SUBMISSION[PROBLEMS_ID.index(problem)] if subTuple[0] == problem_max_submission: flag = 1 return render.index( app_header, "<div class='alert-message error'><a class='close' href='#'>×</a><p>Not allowed to submit more than %s times for this problem!!</p></div>" % (int(problem_max_submission)), app_footer, ) if datetime.timetuple(subTuple[1] + timedelta(seconds=TIME_DIFF)) > localtime(): flag = 1 return render.index( app_header, "<div class='alert-message error'><a class='close' href='#'>×</a><p>Wait for %s seconds between submissions!!</p></div>" % (TIME_DIFF), app_footer, ) count = subTuple[0] + 1 if not flag: cursor.execute( """insert into submission (username, problemid, language, count, program) values (%s, %s, %s, %s, %s)""", (username, problem, language, count, code), ) cursor.close() conn.commit() conn.close() raise web.seeother("/status") except: return render.index( app_header, "<div class='alert-message error'><a class='close' href='#'>×</a><p>Unknown Error Occured!!</p></div>", app_footer, )
def getLastStateAPI(): value={} value['timestamp']=0 value['state']="" activity = models.Activity.query.order_by(models.Activity.timestamp.desc()).limit(1) if activity.count() > 0: activity_model_id = activity[0].activity_model_id tt = datetime.timetuple(activity[0].timestamp) sec_epoch_utc = calendar.timegm(tt) value['timestamp'] = int(sec_epoch_utc) activity_model = models.ActivityModel.query.get(activity_model_id) value['state'] = activity_model.name return json.dumps(value)
def temperatura_historico(request, id_estacion = 1): try: station = Station.objects.get(pk=id_estacion) except Station.DoesNotExist: response_data = {} response_data['status'] = 'error' response_data['message'] = 'No existe la estacion indicada' return HttpResponse(json.dumps(response_data), content_type="application/json") # local_tz = pytz.timezone("America/Asuncion") # pprint.pprint(datetime.now().date()) # pprint.pprint(datetime.fromtimestamp(1393671660).replace(tzinfo=local_tz)) # datos = Data.objects.filter(datetime__lt = datetime.fromtimestamp(1393671660).replace(tzinfo=local_tz)) # datos2 = Data.objects.filter(datetime__lt = datetime.fromtimestamp(1393671660).replace(tzinfo=local_tz)).values('pk', 'datetime', 'rain') # pprint.pprint(datos2) # pprint.pprint('hola mundo') # Date.UTC(year,month,day,hours,minutes,seconds,millisec) # pprint.pprint(datetime.strptime('2012-01-31', '%Y-%m-%d')) #datos = Data.objects.filter(datetime__lt = datetime.fromtimestamp(1393671660).replace(tzinfo=local_tz)) #datos2 = Data.objects.filter(datetime__lt = datetime.fromtimestamp(1393671660).replace(tzinfo=local_tz)).values('pk', 'datetime', 'rain') # request.GET.get('q', '') desde = request.GET.get('desde', datetime.today().strftime("%Y-%m-%d")) desde = datetime.strptime(desde, '%Y-%m-%d') desde = desde.replace(hour=00, minute=01) pprint.pprint(desde) fechaHastaDefault = datetime.today() - timedelta(days=10) hasta = request.GET.get('hasta', fechaHastaDefault.strftime("%Y-%m-%d")) hasta = datetime.strptime(hasta, '%Y-%m-%d') hasta = hasta.replace(hour=23, minute=59) pprint.pprint(hasta) # forzar a que sea una lista el resultado para poder serializar - https://docs.djangoproject.com/en/dev/ref/models/querysets/ datos = list(Data.objects.filter(station = station, datetime__gt = desde, datetime__lt = hasta).values('pk', 'datetime', 'rain', 'outtemp')) result = [] for d in datos: result.append({'pk' : d['pk'], 'datetime' : calendar.timegm(datetime.timetuple(d['datetime'])), 'outtemp' : d['outtemp']}) #result.append({'pk' : d['pk'], 'datetime' : d['datetime'].strftime('%Y-%m-%d %H:%M:%S'), 'outtemp' : d['outtemp']}) response_data = {} response_data['status'] = 'ok' response_data['data'] = result return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type="application/json")
def parsemsgs(self): # parse through all the messages for currmess in self.messages: # first the dates tmpdate = currmess.rawdate[:-5] currmess.date = datetime.strptime(tmpdate,self.dfmt) currmess.date = tz_adjust_EST_EDT(currmess.date,self.tzdata) currmess.dateout = datetime.strftime(currmess.date,self.outfmt) currmess.datestamp = time.mktime(datetime.timetuple(currmess.date)) # now the message bodies cm = currmess.body maxratio = 0 maxrat_count = -99999 # maxrat_line = -99999 line = cm.lower() line = string.rstrip(line,line[string.rfind(line,'sent using sms-to-email'):]) line = re.sub('(\r)',' ',line) line = re.sub('(\n)',' ',line) line = re.sub('(--)',' ',line) if (('ny' in line) or ('by' in line) or ('my' in line) or ('station' in line)): currmess.is_gage_msg = True # we will test the line, but we need to remove some terms using regex substitutions line = re.sub('(ny)','',line) line = re.sub('(by)','',line) line = re.sub('(my)','',line) line = re.sub('(station)','',line) line = re.sub('(water)','',line) line = re.sub('(level)','',line) line = re.sub('(#)','',line) # now get rid of the floating point values that should be the stage # using regex code from: http://stackoverflow.com/questions/385558/ # python-and-regex-question-extract-float-double-value currmess.station_line = line line = re.sub("[+-]? *(?:\d+(?:\.\d*)|\.\d+)(?:[eE][+-]?\d+)?",'', line) for j,cs in enumerate(self.stations): # get the similarity ratio crat = fuzz.ratio(line,cs) if crat > maxratio: maxratio = crat maxrat_count = j currmess.max_prox_ratio = maxratio currmess.closest_station_match = maxrat_count # rip the float out of the line v = re.findall("[+-]? *(?:\d+(?:\.\d*)|\.\d+)(?:[eE][+-]?\d+)?", currmess.station_line) try: currmess.gageheight = float(v[0]) except: continue
def get_last_event_json(): """Returns the details of the last event in the system""" e = db.session.query(models.Event).order_by(models.Event.id.desc()).first() if e is None: return 'No events stored' else: data = {} tt = datetime.timetuple(e.timestamp) sec_epoch_utc = calendar.timegm(tt) data['timestamp'] = int(sec_epoch_utc) data['sensor_name'] = e.fired_by.name data['location'] = e.fired_by.located_in.name data['value'] = e.value return json.dumps(data)
def download_callback(self, response): meta = self.get_meta(response.effective_url) if self.keyword not in meta: meta = '%s %s'%(self.keyword, meta) meta.strip() now = datetime.now() url_title = '%s-%d'%('-'.join(meta.split(' ')[:5]), time.mktime(datetime.timetuple(now))) date = time.strftime("%Y%m%d", datetime.timetuple(now)) date_path = os.path.join(image_ori_path, date) if not os.path.isdir(date_path): os.mkdir(date_path) ori_file = '%s.jpg'%os.path.join( date_path, url_title) fp = file(ori_file, 'wb') fp.write(response.body) fp.close() if self.mark_path: mark = CoreImage.open(self.mark_path) else: mark = None date_path = os.path.join(image_512_path, date) if not os.path.isdir(date_path): os.mkdir(date_path) CoreImage.thumbnail(ori_file, '%s.png'%os.path.join(date_path, url_title), 'PNG', 512, mark, 100) date_path = os.path.join(image_64_path, date) if not os.path.isdir(date_path): os.mkdir(date_path) CoreImage.thumbnail(ori_file, '%s.png'%os.path.join(date_path, url_title), 'PNG', 64) self.save(response.effective_url, meta, date, url_title)
def on_api_sensor(sensor): s = models.Sensor.query.get(sensor) if s is None: return 'Invalid sensor id: {0}'.format(sensor) else: list=s.events.all() for l in list: tt = datetime.timetuple(l.timestamp) sec_epoch_utc = calendar.timegm(tt) l.timestamp=int(sec_epoch_utc) cols = ['id', 'timestamp', 'value'] #Get only the information of the column specified in cols list = [{col: getattr(d, col) for col in cols} for d in list] eventsJS=json.dumps(list,cls=MyEncoder) return eventsJS
def on_api_sensor_interval(sensor,start=1,end=1): s = models.Sensor.query.get(sensor) if s is None: return 'Invalid sensor id: {0}'.format(sensor) else: start=datetime.fromtimestamp(start) end=datetime.fromtimestamp(end) cols = ['id', 'timestamp', 'value'] events = s.events.filter(models.Event.timestamp >start).filter(models.Event.timestamp<end).all() for event in events: tt = datetime.timetuple(event.timestamp) sec_epoch_utc = calendar.timegm(tt) event.timestamp=int(sec_epoch_utc) events = [{col: getattr(d, col) for col in cols} for d in events] eventsJS=json.dumps(events,cls=MyEncoder) return eventsJS
def dateTimeToDocMapper(doc): # Note that you need to include imports used by your mapper # inside the function definition from dateutil.parser import parse from datetime import datetime as dt if doc.get('Date'): # [year, month, day, hour, min, sec] try: parsed = parse(doc['Date']) timetuple = dt.timetuple(parsed) _date = list(timetuple[:-3]) yield (_date, doc) except Exception as e: with open("/Users/cpence/projects/divorce/snitch/data/mbox.couchdb.log", mode='a') as f: f.write('Exception message: %s \n\n\t\tCurrent Document: %s' % (e.message, str(doc['Date'])))
def get_curr_password(): dt = datetime.timetuple(datetime.today()) weekday = dt.tm_wday + 1 monthday = dt.tm_mday month = dt.tm_mon if len(str(month)) == 1: nmonth = int(str(month) + "0") + int(weekday) else: nmonth = int(str(month)[1] + str(month)[0]) + int(weekday) if len(str(monthday)) == 1: nmonthday = int(str(monthday) + "0") + int(weekday) else: nmonthday = int(str(monthday)[1] + str(monthday)[0]) + int(weekday) return str(nmonthday) + str(nmonth)
def insert(self, page): logger.debug('inserting %s'%page.url) json_data = '' now = datetime.now() now_str = strftime("%Y-%m-%d %X", datetime.timetuple(now)) for rtry in xrange(0, 3): try: logger.debug('Connecting to database master.supermario') conn = self.pool_db.get() break except ConnectTimeout: logger.error(Traceback()) if rtry >1 : return self.connector = DatabaseConnector(self.db_pool_conf) self.pool_db = self.connector.get(self.db_name, self.db_table) c = conn.cursor(DictCursor) if not page.author: page.author = u'' if not page.tags: page.tags = u'' data = (('url', page.url), ('url_hash', page.url_hash), ('title', page.title), ('content', page.content), ('author', page.author), ('tags', repr(page.tags)), ('published_at', strftime("%Y-%m-%d %X", datetime.timetuple(page.published_at))), ('identifier', page.identifier), ('inserted_at', now_str),) try: c.execute("SELECT * FROM items WHERE url_hash=%s", (page.url_hash, )) r = c.fetchone() if not r: c.execute("INSERT INTO items (url, url_hash, title, content, author, tags, published_at, identifier, inserted_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (page.url.encode('utf-8').decode('latin1'), page.url_hash.encode('utf-8').decode('latin1'), page.title.encode('utf-8'), page.content.encode('utf-8').decode('latin1'), page.author.encode('utf-8').decode('latin1'), simplejson.dumps(page.tags).encode('utf-8').decode('latin1'), strftime("%Y-%m-%d %X", datetime.timetuple(page.published_at)), page.identifier.encode('utf-8'), now_str, now_str)) logger.debug('inserted %s, %s'%(page.url_hash, page.url)) else: c.execute("UPDATE items SET url=%s, title=%s, content=%s, author=%s, tags=%s, published_at=%s, updated_at=%s, identifier=%s WHERE url_hash=%s", (page.url.encode('utf-8').decode('latin1'), page.title.encode('utf-8').decode('latin1'), page.content.encode('utf-8').decode('latin1'), page.author.encode('utf-8').decode('latin1'), simplejson.dumps(page.tags).encode('utf-8').decode('latin1'), strftime("%Y-%m-%d %X", datetime.timetuple(page.published_at)), now_str, page.identifier.encode('utf-8'), page.url_hash.encode('utf-8').decode('latin1'))) logger.debug('updated %s, %s'%(page.url_hash, page.url)) conn.commit() except: logger.error(Traceback()) finally: try: self.pool_db.put(conn) except: logger.error(Traceback()) c.close() try: json_data = simplejson.dumps(data) except: json_data = '' #self.lightcloud.set(LightCloud.item_key(page.url), json_data) return
def painthms(self): self.canvas.delete(self._ALL) # delete the handles T = datetime.timetuple(datetime.utcnow()-self.delta) x,x,x,h,m,s,x,x,x = T self.root.title('%02i:%02i:%02i' %(h,m,s)) angle = pi/2 - pi/6 * (h + m/60.0) x, y = cos(angle)*0.70,sin(angle)*0.70 scl = self.canvas.create_line # draw the hour handle scl(self.T.windowToViewport(0,0,x,y), fill = self.timecolor, tag=self._ALL, width = self.pad/3) angle = pi/2 - pi/30 * (m + s/60.0) x, y = cos(angle)*0.90,sin(angle)*0.90 # draw the minute handle scl(self.T.windowToViewport(0,0,x,y), fill = self.timecolor, tag=self._ALL, width = self.pad/5) angle = pi/2 - pi/30 * s x, y = cos(angle)*0.95,sin(angle)*0.95 # draw the second handle scl(self.T.windowToViewport(0,0,x,y), fill = self.timecolor, tag=self._ALL, arrow = 'last')
def browse_collection(self, host, port, dbname, collection_name, page, step): try: c = MongoConnection(host=host, port=int(port), pool_size=1) db = database.Database(c, dbname) cl = MongoCollection.Collection(db, collection_name) res = cl.find(skip = (int(page) -1) * int(step), limit = int(step)) entries = [] for r in res: tmp = {} for k, v in r.items(): if isinstance(v, datetime): tmp[k] = strftime('%Y-%m-%d %X', datetime.timetuple(v)) else: tmp[k] = v entries.append(tmp) return {'count':cl.count(), 'entries': entries} except Exception, err: return -1
def painthms(self): self.canvas.delete('hms') # delete the hands T = datetime.timetuple(datetime.utcnow() - timedelta(hours = 5)) x,x,x,h,m,s,x,x,x = T if h != self.hour: self.hour = h # update hour circle self.clock_finishings_decorate() if (h % 6 == 0 or h == 0): layout = Layout(self.root, 3, True, self.givenWidth, self.givenHeight) # update the weather every 6 hours layout.updateWeather() # update verse and quote every day if h == 12: layout.updateQuoteAndVerse() self.root.title('%02i:%02i:%02i' %(h,m,s)) scl = self.canvas.create_line # draw the hour hand angle = pi/2 - pi/6 * (h + m/60.0) x, y = cos(angle)*0.60, sin(angle)*0.60 scl(self.T.windowToViewport(0,0,x,y), fill = '#06CFEF', tag = 'hms', width = self.pad/4) # draw the minute hand angle = pi/2 - pi/30 * (m + s/60.0) x, y = cos(angle)*0.80, sin(angle)*0.80 scl(self.T.windowToViewport(0,0,x,y), fill = '#06CFEF', tag = 'hms', width = self.pad/6) # draw the second hand angle = pi/2 - pi/30 * s x, y = cos(angle)*0.85, sin(angle)*0.85 scl(self.T.windowToViewport(0,0,x,y), fill = '#06CFEF', tag = 'hms')
def painthms(self): self.canvas.delete('hms') # delete the hand T = datetime.timetuple(datetime.utcnow() - timedelta(hours = 0)) x,x,x,h,m,s,x,x,x = T self.root.title('%02i:%02i:%02i' %(h,m,s)) scl = self.canvas.create_line # draw the hour hand angle = pi/2 - pi/6 * (h + m/60.0) x, y = cos(angle)*0.70, sin(angle)*0.70 scl(self.T.windowToViewport(0,0,x,y), fill = '#18CAE6', tag = 'hms', width = self.pad/3) # draw the minute hand angle = pi/2 - pi/30 * (m + s/60.0) x, y = cos(angle)*0.90, sin(angle)*0.90 scl(self.T.windowToViewport(0,0,x,y), fill = '#18CAE6', tag = 'hms', width = self.pad/5) # draw the second hand angle = pi/2 - pi/30 * s x, y = cos(angle)*0.95, sin(angle)*0.95 scl(self.T.windowToViewport(0,0,x,y), fill = '#18CAE6', tag = 'hms')