def test_epoch_to_local(self): """ Tests out the epoch_to_local() method of the Model class. """ from time import time time = self.model.epoch_to_local(time()) date, time = time.split() date = date.split('-') time = time.split(':') datetime = list(map(int, date + time)) self.assertEqual(len(datetime), 6)
def diff2 (self, time): date = str(time).split(" ")[0] y = int(date.split("-")[0]) m = int(date.split("-")[1]) d = int(date.split("-")[2]) if y==2014 and m == 1 and d == 1: time = str(time).split(" ")[1] h= int(time.split(":")[0]) m= int(time.split(":")[1]) s= time.split(":")[2] if h >= 120 and h <=216 : return True else: return False
def diff2(self, time): date = str(time).split(" ")[0] y = int(date.split("-")[0]) m = int(date.split("-")[1]) d = int(date.split("-")[2]) if y == 2014 and m == 1 and d == 1: time = str(time).split(" ")[1] h = int(time.split(":")[0]) m = int(time.split(":")[1]) s = time.split(":")[2] if h >= 120 and h <= 216: return True else: return False
def AssessRecord(line): line = line.rstrip("\n") values = line.split("|") ## Computing Time time = values[2].split()[1] time = time.split(":") hh = int(time[0]) mm = int(time[1]) time = hh*60 + mm ## Computing Day date = values[2].split()[0].split("/") year = int(date[2]) month = int(date[0]) day = int(date[1]) ## Mondays are (100 + day_value) ## Tuesdays are (200 + day_value) ## Wednesdays are (300 + day_value) etc..... computed_day = int(datetime(year,month,day).date().isoweekday() * 100 + day) link_id = int(values[3]) occupancy = int(values[4]) speed = int(values[5]) volume = int(values[6]) record = [] if link_id in links_specifics: record = [link_id,year,month,computed_day,time,occupancy,speed,volume] return record
def datestr2list(datestr): ''' Take strings of the form: "2013/1/18 20:08:18" and return them as a tuple of the same parameters''' year,month,others = datestr.split('/') day, time = others.split(' ') hour,minute,sec = time.split(':') return (int(year),int(month),int(day),int(hour),int(minute),int(sec))
def date_to_comparable(time): time = time.split() if time[2] == 'Jan': time[2] = '01' if time[2] == 'Feb': time[2] = '02' if time[2] == 'Mar': time[2] = '03' if time[2] == 'Apr': time[2] = '04' if time[2] == 'May': time[2] = '05' if time[2] == 'Jun': time[2] = '06' if time[2] == 'Jul': time[2] = '07' if time[2] == 'Aug': time[2] = '08' if time[2] == 'Sep': time[2] = '09' if time[2] == 'Oct': time[2] = '10' if time[2] == 'Nov': time[2] = '11' if time[2] == 'Dec': time[2] = '12' return (time[3] + time[2] + '%2d' + time[0]) % int(time[1])
def timeToSecs(time): units = time.split(":") i = 0 secs = 0 for unit in reversed(units): secs += pow(60, i) * int(unit) i += 1 return secs
def diff1(self, time): date = str(time).split(" ")[0] y = int(date.split("-")[0]) - 2014 m = int(date.split("-")[1]) - 1 d = int(date.split("-")[2]) - 1 d = d + y * 365 + m * 30 time = str(time).split(" ")[1] h = int(time.split(":")[0]) m = int(time.split(":")[1]) s = time.split(":")[2] h = h + (d * 24) if h >= 1 and h <= 3744: return True else: return False
def parse_time_string(self, time, strip_date=True): '''Parses the time string to reasonable format. ''' time = time.split("T") if len(time) == 2 and not strip_date: date, time = time return " ".join((time, date)) return time[-1]
def get_time(t, tz_map=tz_map, cache={}): date, time, zone = t.split() zone = tz_map.get(zone, zone) if zone in cache: zone = cache[zone] else: zone = cache.setdefault(zone, timezone(zone)) d = zone.localize(datetime(*map(int, (date.split('/') + time.split(':'))))) return int(mktime(d.timetuple()) * 1000)
def parse_time_string(self, time, strip_date=True): '''Parses the time string to reasonable format. ''' time = time.split("T") if len(time) == 2 and not strip_date: date, time = time return " ".join((time, date)) # return time return time[-1]
def diff1 (self, time): date = str(time).split(" ")[0] y = int(date.split("-")[0]) - 2014 m = int(date.split("-")[1]) - 1 d = int(date.split("-")[2]) - 1 d = d + y*365 + m*30 time = str(time).split(" ")[1] h= int(time.split(":")[0]) m= int(time.split(":")[1]) s= time.split(":")[2] h = h + ( d * 24 ) if h >= 1 and h <= 3744: return True else: return False
def update(self, ph=0.0, ec=0.0, temp=0.0, co2=0.0, hum=0.0, error_type = 7000, error=False): if error: self.errors.append(error_type) self.local_time = datetime.datetime.now(pytz.timezone('Asia/Seoul')) time = str(self.local_time) tmp1 = time.split(" ") tmp2 = tmp1[1].split(":") self.localMin = int(tmp2[1]) self.localHour = int (tmp2[0]) else: self.local_time = datetime.datetime.now(pytz.timezone('Asia/Seoul')) time = str(self.local_time) tmp1 = time.split(" ") tmp2 = tmp1[1].split(":") self.localMin = int(tmp2[1]) self.localHour = int(tmp2[0]) self.ph = ph self.ec = ec self.liquid_temperature = temp self.co2 = co2 self.hum = hum pass
def give_part_of_day(): """ It gives current part of day. """ time=str(datetime.now()).split()[-1] h=[int(j) for j in time.split(':')[:-1]][0] part_of_day="" if(h<12): part_of_day="Morning" elif(h<16): part_of_day="After Noon" else: part_of_day="Evening" return part_of_day,h
def gat2dt(gat): """ Convert grads time to datetime. """ time, date = gat.upper().split('Z') if time.count(':') > 0: h, m = time.split(":") else: h = time m = '0' mmm = date[-7:-4] dd, yy = date.split(mmm) mm = __Months__.index(mmm) + 1 dt = datetime(int(yy), int(mm), int(dd), int(h), int(m)) return dt
def deconverting_time(time: str): """ Декодирование окончания в секунды """ _str = time.split() sec = 0 if len(_str) == 2: if _str[1] == "час": sec += 3600 elif _str[1] == "часа": if len(_str) == 2: sec += int(_str[0]) * 3600 elif _str[1] == "мин": sec = 1800 else: sec += (int(_str[0]) * 3600) + 1800 return sec
def parse_time(value, tzinfo): """Parse Twitter API time format. >>> parse_time("Sun Dec 14 11:29:30 +0000 2008", StaticTzInfo(0)) datetime(2008, 12, 14, 11, 29, 30) >>> parse_time("Sun Dec 14 11:29:30 +0000 2008", StaticTzInfo(8)) datetime(2008, 12, 22, 11, 29, 30) """ if not value: return None day, month, date, time, timezone, year = value.lower().split() hour, min, sec = time.split(u":") utc_dt = datetime(int(year), int(MONTHS[month]), int(date), int(hour), int(min), int(sec)) return tzinfo.localize(utc_dt)
def _setup_mmss_time(self, form=None): """ Setup the formatted time string. """ time = str(datetime.timedelta(seconds=self.timer)) components = time.split(":") if time[0] == "0": time = ":".join(components[1:]) if form == "mm": time = components[-2] else: if form == "mm": time = int(components[0]) * 60 + int(components[-2]) return time
def _setup_mmss_time(self, form=None): """ Setup the formatted time string. """ time = str(datetime.timedelta(seconds=self.timer)) components = time.split(':') if time[0] == '0': time = ':'.join(components[1:]) if form == 'mm': time = components[-2] else: if form == 'mm': time = int(components[0]) * 60 + int(components[-2]) return time
def _validate_start_stop(self, start, stop): try: for x in [start, stop]: if x: month, date, time, year = start.split(" ") assert (month.istitle()) assert (len(month) == 3) assert (date.isnumeric()) assert (len(date) == 2) for t in time.split(":"): assert (t.isnumeric()) assert (len(t) == 2) assert (year.isnumeric()) assert (len(year) == 4) except: raise Exception('start/stop must be of the form'+\ ' "Month DD HH:MM:SS YYYY" (eg. "Dec 31 23:59:59 2021")')
def store_data(data: tuple, store: list): try: artist = data[0].pop("artist") album = data[0].pop("album") song = data[0].pop("title") time = data[1].pop("time") state = data[1].pop("state") elapse, duration = (int(x) for x in time.split(":")) li = ((artist, album, song), elapse, duration) except KeyError: state = "turnedoff" if state == "play": store.append(li) if len(store) > 2: print(store[0]) print(store[1]) print(store[2]) a = store.remove(store[1]) # print(store[0][0][2], store[0]) # print(store_) # store.remove(store[1:3]) # store.remove(store[1]) # store.remove(store[2]) # store.remove(store[3]) print(store) print("-" * 10) # else: # print(store, len(store)) elif state == "pause": print("player on pause") elif state == "turnedoff": print("Player turned off") sleep(5) else: print("looks like player stop")
def splitDateTime(dateTime): spl = dateTime.split() date = spl[0] time = spl[1] spl = date.split("-") year = int(spl[0]) month = int(spl[1]) day = int(spl[2]) spl = time.split(":") hour = int(spl[0]) minute = int(spl[1]) second = int(spl[2].split(".")[0]) dtm = datetime(year, month, day, hour, minute, second) timestamp = dtm.timestamp() weekd = dtm.weekday() days = [ "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche" ] weekd = days[weekd] return timestamp, weekd, year, month, day, hour, minute, second
def parse_time(self, time): time = time.split('(')[0] hours, mins, secs = [int(x) for x in time.split(':')] return str(3600 * hours + 60 * mins + secs)
def parse_time(time): return ''.join(time.split('-')).split(' ')
def ingest(self): """Ingest the contents of the current work log. Arguments: None Returns: None Populates: self """ # try try: # to retrieve the current file with open(self.path, 'r') as pointer: # get lines lines = pointer.readlines() # unless it doesn't exit except FileNotFoundError: # create file with open(self.path, 'w') as pointer: # write blank lines = [] pointer.writelines(lines) # remove returns lines = [line.strip() for line in lines] lines += [''] # break lines into days days = [] day = {'entries': []} for line in lines: # check for blank or total line if line == '' or line.startswith('Total'): # add current day to days days.append(day) day = {'entries': []} # otherwise else: # check for first day if 'date' not in day.keys(): # get a date object date = datetime.strptime(line.split()[1], '%m/%d/%Y') # assume date is first line day.update({'date': date}) # otherwise assume a time row else: # begin entry entry = {} # get start time time = line.split('-')[0].strip() hour, minute = time.split(':') start = day['date'].replace(hour=int(hour), minute=int(minute), second=0, microsecond=0) entry['start'] = start # default finish to same finish = start entry['finish'] = finish # if not in discrete mode if not self.discrete: # get finish time time = line.split('-')[1].split(')')[0].strip() hour, minute = time.split(':') finish = day['date'].replace(hour=int(hour), minute=int(minute), second=0, microsecond=0) entry['finish'] = finish # calculate duration duration = (finish - start).total_seconds() / (60 * 60) # adjust for negative durations duration += 24 * int(duration < 0) entry['duration'] = duration # make note entry entry['note'] = line.split(')')[1].strip() # add to current day day['entries'].append(entry) # depopulate instance while len(self) > 0: # popoff self.pop() # repopulate for day in days: # filter out blanks if len(day['entries']) > 0: # append to self self.append(day) return None
def _date_time_str_to_datetime64_gen(date, time): mm, dd, yy = date.split('/') HH, MM = time.split(':') yr = str(2000 + int(yy)) yield np.datetime64(f'{yr}-{mm}-{dd}T{HH}:{MM}:00')
def _date_time_str_to_datetime64_alt(date, time): mm, dd, yy = date.split('/') HH, MM = time.split(':') dt = datetime(int(yy) + 2000, int(mm), int(dd), int(HH), int(MM), 0) return np.datetime64(dt).astype('datetime64[s]')
def iso_time_parse(time): time = time.split(':') time.extend(time.pop().split('.')) return map(int, time)
# Display logs per ANN print( f"Finished epoch nº{iteration + 1}; final batch avg.cost = {'%.9f' % cost}; epoch cost = {epoch_cost / batch}\n" ) print("Output weights: ", W_out.eval(), "\n") print("Output betas: ", b_out.eval(), "\n") if args.log is not False: print( f"For visualization on TensorBoard, type: tensorboard --logdir={args.log}/\n" ) if args.save is not False: # save the model date, time = str(datetime.now()).split() datetime = date.replace( '-', '_') + '_' + time.split('.')[0].replace(':', '_') saver.save(sess, f"saved_models/{model_id}/{model_id}_{datetime}") if args.test is not False: ## Test the ANN and calculate accuracy print(f"Testing accuracy...\n") predictions = tf.equal(tf.argmax(model_out, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(predictions, "float")) with gzip.open(f"{args.test}.test.gz", "rt") as testing_genotypes, \ gzip.open(f"{args.test}.pops.test.gz", "rt") as testing_pops: batch_genos = np.genfromtxt(testing_genotypes, max_rows=testing_batch_size, dtype=float)
re.IGNORECASE) data = re.search(lineformat, line) #Cleaning the data for easy use data = data.groupdict() if data["request"] == '"GET': data["request"] = "GET" if data["ipaddress"] not in ips: ips.append(data["ipaddress"]) ip_address = data["ipaddress"] time = data["dateandtime"] request = data["request"] t = time.split() struct_time = strptime(t[0], "%d/%b/%Y:%H:%M:%S") iso_8601_time = "{}-{}-{}T{}:{}:{}+{}:{}".format( struct_time.tm_year, struct_time.tm_mon, struct_time.tm_mday, struct_time.tm_hour, struct_time.tm_min, struct_time.tm_sec, t[1][1:3], t[1][-2:]) parsed_time = dp.parse(iso_8601_time) t_in_seconds = float(parsed_time.strftime("%S")) if request == "GET": if ip_address not in ips_dict: ips_dict[ip_address] = { "start_time": t_in_seconds, "end_time": 0, "time_difference": 0,
def parse_time(self, date, time): # The hard part - let's try to make sense of these times # Thankfully, we only care if we can resolve to an exact date, # and those at least stay pretty consistent. if date.startswith('NET '): date = date[len('NET '):] # date format has been observed like the following: # Feb. 22 # March 1 # March 6/7 (in which case time str may have "on %dth" suffix) # In this case we assume the latter day, since they're generally reporting UTC/ET # Further to simplify, we cut off at the first / and assume latter is former + 1 if '/' in date: date = date.split('/', 1)[0] fix_up = 60 * 60 * 24 else: fix_up = 0 date_formats = ['%b. %d', '%B %d'] for fmt in date_formats: try: time_tuple = strptime(date, fmt) except ValueError: pass else: break else: return # year in yearless formats is arbitrary but hopefully consistent, so normalize days = timegm(time_tuple) - timegm(strptime('1 1', '%m %d')) + fix_up # time format has been observed like the following: # %H%M GMT # %H%M:%S GMT # %H%M-%H%M GMT, expressing a range. We only want the first part. # We can safely assume it's two words, with the former the time. # We can then easily split if it's a range and keep start. time = time.split(' ', 1)[0] time = time.split('-', 1)[0] time_formats = ['%H%M', '%H%M:%S'] for fmt in time_formats: try: time_tuple = strptime(time, fmt) except ValueError: pass else: break else: return # date in dateless formats is arbitrary but hopefully consistent, so normalize time = timegm(time_tuple) - timegm(strptime('0000', '%H%M')) # put it all together. if it's already passed > 7 days ago, assume it means next year date = days + time now = gmtime() get_year_time = lambda year: timegm(strptime(str(year), '%Y')) timestamp = get_year_time(now.tm_year) + date if timegm(now) - timestamp > 60 * 60 * 24 * 7: timestamp = get_year_time(now.tm_year + 1) + date return timestamp